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/async/AsyncExecutionModule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.async; import org.sonar.core.platform.Module; public class AsyncExecutionModule extends Module { @Override protected void configureModule() { add( AsyncExecutionMBeanImpl.class, AsyncExecutionExecutorServiceImpl.class, AsyncExecutionImpl.class); } }
1,148
33.818182
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/async/AsyncExecutionMonitoring.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.async; public interface AsyncExecutionMonitoring { int getQueueSize(); int getWorkerCount(); int getLargestWorkerCount(); }
1,001
33.551724
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/async/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.async; import javax.annotation.ParametersAreNonnullByDefault;
962
39.125
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/component/index/ComponentDoc.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.component.index; import java.util.HashMap; import java.util.Map; import org.sonar.server.es.BaseDoc; import org.sonar.server.permission.index.AuthorizationDoc; import static org.sonar.server.component.index.ComponentIndexDefinition.FIELD_KEY; import static org.sonar.server.component.index.ComponentIndexDefinition.FIELD_NAME; import static org.sonar.server.component.index.ComponentIndexDefinition.FIELD_QUALIFIER; import static org.sonar.server.component.index.ComponentIndexDefinition.FIELD_UUID; import static org.sonar.server.component.index.ComponentIndexDefinition.TYPE_COMPONENT; public class ComponentDoc extends BaseDoc { public ComponentDoc() { super(TYPE_COMPONENT, new HashMap<>(6)); } /** * Needed for reflection. Do not remove. */ public ComponentDoc(Map<String, Object> fields) { super(TYPE_COMPONENT, fields); } @Override public String getId() { return getField(FIELD_UUID); } public ComponentDoc setId(String s) { setField(FIELD_UUID, s); setParent(AuthorizationDoc.idOf(s)); return this; } public String getKey() { return getField(FIELD_KEY); } public ComponentDoc setKey(String s) { setField(FIELD_KEY, s); return this; } public String getName() { return getField(FIELD_NAME); } public ComponentDoc setName(String s) { setField(FIELD_NAME, s); return this; } public String getQualifier() { return getField(FIELD_QUALIFIER); } public ComponentDoc setQualifier(String s) { setField(FIELD_QUALIFIER, s); return this; } public ComponentDoc setAuthUuid(String s) { setParent(AuthorizationDoc.idOf(s)); return this; } }
2,538
27.52809
88
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/component/index/ComponentHit.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.component.index; import java.util.List; import java.util.Optional; import org.elasticsearch.common.text.Text; import org.elasticsearch.search.SearchHit; import static java.util.Arrays.stream; import static java.util.Optional.ofNullable; import static org.sonar.server.component.index.ComponentIndexDefinition.FIELD_NAME; public class ComponentHit { private final String uuid; private final Optional<String> highlightedText; public ComponentHit(String uuid) { this.uuid = uuid; this.highlightedText = Optional.empty(); } public ComponentHit(SearchHit hit) { this.uuid = hit.getId(); this.highlightedText = getHighlightedText(hit); } private static Optional<String> getHighlightedText(SearchHit hit) { return ofNullable(hit.getHighlightFields()) .flatMap(fields -> ofNullable(fields.get(FIELD_NAME))) .flatMap(field -> ofNullable(field.getFragments())) .flatMap(fragments -> stream(fragments).findFirst()) .map(Text::string); } public String getUuid() { return uuid; } public static List<ComponentHit> fromSearchHits(SearchHit... hits) { return stream(hits) .map(ComponentHit::new) .toList(); } public Optional<String> getHighlightedText() { return highlightedText; } }
2,142
30.514706
83
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/component/index/ComponentHitsPerQualifier.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.component.index; import java.util.List; public class ComponentHitsPerQualifier { private final String qualifier; private final List<ComponentHit> hits; private final long totalHits; public ComponentHitsPerQualifier(String qualifier, List<ComponentHit> hits, long totalHits) { this.qualifier = qualifier; this.hits = hits; this.totalHits = totalHits; } public String getQualifier() { return qualifier; } public List<ComponentHit> getHits() { return hits; } public long getTotalHits() { return totalHits; } }
1,428
28.770833
95
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/component/index/ComponentIndexDefinition.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.component.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.newindex.DefaultIndexSettingsElement; import org.sonar.server.es.newindex.NewAuthorizedIndex; import org.sonar.server.es.newindex.TypeMapping; import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.SEARCH_GRAMS_ANALYZER; import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.SEARCH_PREFIX_ANALYZER; import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.SEARCH_PREFIX_CASE_INSENSITIVE_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 static org.sonar.server.permission.index.IndexAuthorizationConstants.TYPE_AUTHORIZATION; import javax.inject.Inject; public class ComponentIndexDefinition implements IndexDefinition { public static final Index DESCRIPTOR = Index.withRelations("components"); public static final IndexType.IndexRelationType TYPE_COMPONENT = IndexType.relation(IndexType.main(DESCRIPTOR, TYPE_AUTHORIZATION), "component"); public static final String FIELD_UUID = "uuid"; public static final String FIELD_KEY = "key"; public static final String FIELD_NAME = "name"; public static final String FIELD_QUALIFIER = "qualifier"; private static final int DEFAULT_NUMBER_OF_SHARDS = 5; private final int numberOfShards; static final DefaultIndexSettingsElement[] NAME_ANALYZERS = {SORTABLE_ANALYZER, SEARCH_PREFIX_ANALYZER, SEARCH_PREFIX_CASE_INSENSITIVE_ANALYZER, SEARCH_GRAMS_ANALYZER}; private final Configuration config; private final boolean enableSource; private ComponentIndexDefinition(Configuration config, boolean enableSource, int numberOfShards) { this.config = config; this.enableSource = enableSource; this.numberOfShards = numberOfShards; } @Inject public ComponentIndexDefinition(Configuration config) { this(config, false, DEFAULT_NUMBER_OF_SHARDS); } /** * Keep the document sources in index so that indexer tests can verify content * of indexed documents. */ public static ComponentIndexDefinition createForTest() { // different shards can have different scoring, affecting tests, so we use a single shard return new ComponentIndexDefinition(new MapSettings().asConfig(), true, 1); } @Override public void define(IndexDefinitionContext context) { NewAuthorizedIndex index = context.createWithAuthorization( DESCRIPTOR, newBuilder(config) .setRefreshInterval(MANUAL_REFRESH_INTERVAL) .setDefaultNbOfShards(numberOfShards) .build()) .setEnableSource(enableSource); TypeMapping mapping = index.createTypeMapping(TYPE_COMPONENT); mapping.keywordFieldBuilder(FIELD_UUID).disableNorms().build(); mapping.keywordFieldBuilder(FIELD_KEY).addSubFields(SORTABLE_ANALYZER).build(); mapping.textFieldBuilder(FIELD_NAME) .withFieldData() // required by highlighting .store() .termVectorWithPositionOffsets() .addSubFields(NAME_ANALYZERS) .build(); mapping.keywordFieldBuilder(FIELD_QUALIFIER).build(); } }
4,306
41.22549
170
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/component/index/EntityDefinitionIndexer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.component.index; import com.google.common.annotations.VisibleForTesting; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.entity.EntityDto; import org.sonar.db.es.EsQueueDto; import org.sonar.server.es.AnalysisIndexer; import org.sonar.server.es.BaseDoc; 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.IndexingResult; import org.sonar.server.es.OneToManyResilientIndexingListener; import org.sonar.server.permission.index.AuthorizationDoc; import org.sonar.server.permission.index.AuthorizationScope; import org.sonar.server.permission.index.NeedAuthorizationIndexer; import static java.util.Collections.emptyList; import static org.sonar.server.component.index.ComponentIndexDefinition.TYPE_COMPONENT; /** * Indexes the definition of all entities: projects, applications, portfolios and sub-portfolios. */ public class EntityDefinitionIndexer implements EventIndexer, AnalysisIndexer, NeedAuthorizationIndexer { private static final AuthorizationScope AUTHORIZATION_SCOPE = new AuthorizationScope(TYPE_COMPONENT, entity -> true); private static final Set<IndexType> INDEX_TYPES = Set.of(TYPE_COMPONENT); private final DbClient dbClient; private final EsClient esClient; public EntityDefinitionIndexer(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) { doIndexByEntityUuid(Size.LARGE); } public void indexAll() { doIndexByEntityUuid(Size.REGULAR); } @Override public void indexOnAnalysis(String branchUuid) { indexOnAnalysis(branchUuid, Set.of()); } @Override public void indexOnAnalysis(String branchUuid, Set<String> unchangedComponentUuids) { try (DbSession dbSession = dbClient.openSession(false)) { Optional<BranchDto> branchDto = dbClient.branchDao().selectByUuid(dbSession, branchUuid); if (branchDto.isPresent() && !branchDto.get().isMain()) { return; } EntityDto entity = dbClient.entityDao().selectByComponentUuid(dbSession, branchUuid) .orElseThrow(() -> new IllegalStateException("Can't find entity for branch " + branchUuid)); doIndexByEntityUuid(entity); } } @Override public AuthorizationScope getAuthorizationScope() { return AUTHORIZATION_SCOPE; } @Override public Collection<EsQueueDto> prepareForRecoveryOnEntityEvent(DbSession dbSession, Collection<String> entityUuids, Indexers.EntityEvent cause) { return switch (cause) { case PROJECT_TAGS_UPDATE, PERMISSION_CHANGE -> // measures, tags and permissions does not affect the definition of entities emptyList(); case CREATION, DELETION, PROJECT_KEY_UPDATE -> { List<EsQueueDto> items = createEsQueueDtosFromEntities(entityUuids); yield dbClient.esQueueDao().insert(dbSession, items); } }; } private static List<EsQueueDto> createEsQueueDtosFromEntities(Collection<String> entityUuids) { return entityUuids.stream() .map(entityUuid -> EsQueueDto.create(TYPE_COMPONENT.format(), entityUuid, null, entityUuid)) .toList(); } @Override public Collection<EsQueueDto> prepareForRecoveryOnBranchEvent(DbSession dbSession, Collection<String> branchUuids, Indexers.BranchEvent cause) { return emptyList(); } @Override public IndexingResult index(DbSession dbSession, Collection<EsQueueDto> items) { if (items.isEmpty()) { return new IndexingResult(); } OneToManyResilientIndexingListener listener = new OneToManyResilientIndexingListener(dbClient, dbSession, items); BulkIndexer bulkIndexer = new BulkIndexer(esClient, TYPE_COMPONENT, Size.REGULAR, listener); bulkIndexer.start(); Set<String> entityUuids = items.stream().map(EsQueueDto::getDocId).collect(Collectors.toSet()); Set<String> remaining = new HashSet<>(entityUuids); dbClient.entityDao().selectByUuids(dbSession, entityUuids).forEach(dto -> { remaining.remove(dto.getUuid()); bulkIndexer.add(toDocument(dto).toIndexRequest()); }); // the remaining uuids reference projects that don't exist in db. They must // be deleted from index. remaining.forEach(projectUuid -> addProjectDeletionToBulkIndexer(bulkIndexer, projectUuid)); return bulkIndexer.stop(); } /** * @param entity the entity to analyze, or {@code null} if all content should be indexed.<br/> * <b>Warning:</b> only use {@code null} during startup. */ private void doIndexByEntityUuid(EntityDto entity) { BulkIndexer bulk = new BulkIndexer(esClient, TYPE_COMPONENT, Size.REGULAR); bulk.start(); try (DbSession dbSession = dbClient.openSession(false)) { bulk.add(toDocument(entity).toIndexRequest()); if (entity.getQualifier().equals("VW")) { dbClient.portfolioDao().selectTree(dbSession, entity.getUuid()).forEach(sub -> bulk.add(toDocument(sub).toIndexRequest())); } } bulk.stop(); } private void doIndexByEntityUuid(Size bulkSize) { BulkIndexer bulk = new BulkIndexer(esClient, TYPE_COMPONENT, bulkSize); bulk.start(); try (DbSession dbSession = dbClient.openSession(false)) { dbClient.entityDao().scrollForIndexing(dbSession, context -> { EntityDto dto = context.getResultObject(); bulk.add(toDocument(dto).toIndexRequest()); }); } bulk.stop(); } private static void addProjectDeletionToBulkIndexer(BulkIndexer bulkIndexer, String projectUuid) { SearchRequest searchRequest = EsClient.prepareSearch(TYPE_COMPONENT.getMainType()) .source(new SearchSourceBuilder().query(QueryBuilders.termQuery(ComponentIndexDefinition.FIELD_UUID, projectUuid))) .routing(AuthorizationDoc.idOf(projectUuid)); bulkIndexer.addDeletion(searchRequest); } @VisibleForTesting void index(EntityDto... docs) { BulkIndexer bulk = new BulkIndexer(esClient, TYPE_COMPONENT, Size.REGULAR); bulk.start(); Arrays.stream(docs) .map(EntityDefinitionIndexer::toDocument) .map(BaseDoc::toIndexRequest) .forEach(bulk::add); bulk.stop(); } public static ComponentDoc toDocument(EntityDto entity) { return new ComponentDoc() .setId(entity.getUuid()) .setAuthUuid(entity.getAuthUuid()) .setName(entity.getName()) .setKey(entity.getKey()) .setQualifier(entity.getQualifier()); } }
8,001
35.875576
146
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/component/index/SuggestionQuery.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.component.index; import java.util.Collection; import java.util.Collections; import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; public class SuggestionQuery { public static final int DEFAULT_LIMIT = 6; private final String query; private final Collection<String> qualifiers; private final Set<String> recentlyBrowsedKeys; private final Set<String> favoriteKeys; private final int skip; private final int limit; private SuggestionQuery(Builder builder) { this.query = requireNonNull(builder.query); this.qualifiers = requireNonNull(builder.qualifiers); this.recentlyBrowsedKeys = requireNonNull(builder.recentlyBrowsedKeys); this.favoriteKeys = requireNonNull(builder.favoriteKeys); this.skip = builder.skip; this.limit = builder.limit; } public Collection<String> getQualifiers() { return qualifiers; } public String getQuery() { return query; } public Set<String> getRecentlyBrowsedKeys() { return recentlyBrowsedKeys; } public int getSkip() { return skip; } public int getLimit() { return limit; } public static Builder builder() { return new Builder(); } public Set<String> getFavoriteKeys() { return favoriteKeys; } public static class Builder { private String query; private Collection<String> qualifiers = Collections.emptyList(); private Set<String> recentlyBrowsedKeys = Collections.emptySet(); private Set<String> favoriteKeys = Collections.emptySet(); private int skip = 0; private int limit = DEFAULT_LIMIT; private Builder() { } public Builder setQuery(String query) { checkArgument(query.length() >= 2, "Query must be at least two characters long: %s", query); this.query = query; return this; } public Builder setQualifiers(Collection<String> qualifiers) { this.qualifiers = Collections.unmodifiableCollection(qualifiers); return this; } public Builder setRecentlyBrowsedKeys(Set<String> recentlyBrowsedKeys) { this.recentlyBrowsedKeys = Collections.unmodifiableSet(recentlyBrowsedKeys); return this; } public Builder setFavoriteKeys(Set<String> favoriteKeys) { this.favoriteKeys = Collections.unmodifiableSet(favoriteKeys); return this; } public Builder setSkip(int skip) { checkArgument(limit > 0, "Skip has to be strictly positive: %s", limit); this.skip = skip; return this; } public Builder setLimit(int limit) { checkArgument(limit > 0, "Limit has to be strictly positive: %s", limit); this.limit = limit; return this; } public SuggestionQuery build() { return new SuggestionQuery(this); } } }
3,674
28.166667
98
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/component/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.component.index; import javax.annotation.ParametersAreNonnullByDefault;
972
39.541667
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/config/ConfigurationProvider.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.config; import static java.util.function.UnaryOperator.identity; import org.apache.commons.lang.ArrayUtils; import org.sonar.api.config.Configuration; import org.sonar.api.config.PropertyDefinition; import static org.sonar.api.config.internal.MultivalueProperty.parseAsCsv; import org.sonar.api.config.internal.Settings; import org.springframework.context.annotation.Bean; import java.util.Optional; import java.util.function.UnaryOperator; public class ConfigurationProvider { @Bean("Configuration") public Configuration provide(Settings settings) { return new ServerConfigurationAdapter(settings); } private static class ServerConfigurationAdapter implements Configuration { private static final UnaryOperator<String> REPLACE_ENCODED_COMMAS = value -> value.replace("%2C", ","); private final Settings settings; private ServerConfigurationAdapter(Settings settings) { this.settings = settings; } @Override public Optional<String> get(String key) { return Optional.ofNullable(settings.getString(key)); } @Override public boolean hasKey(String key) { return settings.hasKey(key); } @Override public String[] getStringArray(String key) { boolean multiValue = settings.getDefinition(key) .map(PropertyDefinition::multiValues) .orElse(false); return get(key) .map(v -> parseAsCsv(key, v, multiValue ? REPLACE_ENCODED_COMMAS : identity())) .orElse(ArrayUtils.EMPTY_STRING_ARRAY); } } }
2,389
32.661972
107
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/config/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.config; import javax.annotation.ParametersAreNonnullByDefault;
963
39.166667
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/email/BasicEmail.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.email; import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; public class BasicEmail { private final Set<String> recipients; protected BasicEmail(Set<String> recipients) { checkArgument(!recipients.isEmpty(), "At least one recipient must be provided."); this.recipients = recipients; } public Set<String> getRecipients() { return recipients; } }
1,275
32.578947
85
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/email/EmailSender.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.email; import org.apache.commons.mail.Email; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; import org.apache.commons.mail.MultiPartEmail; import org.sonar.api.config.EmailSettings; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.commons.lang.StringUtils.equalsIgnoreCase; import static org.apache.commons.lang.StringUtils.isBlank; import static org.apache.commons.lang.StringUtils.isNotBlank; import java.net.MalformedURLException; public abstract class EmailSender<T extends BasicEmail> { protected static final int SOCKET_TIMEOUT = 30_000; protected final EmailSettings emailSettings; protected EmailSender(EmailSettings emailSettings) { this.emailSettings = emailSettings; } public void send(T report) { // Trick to correctly initialize javax.mail library ClassLoader classloader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); try { Email email = createEmail(report); email.send(); } catch (MalformedURLException | EmailException e) { throw new IllegalStateException(e); } finally { Thread.currentThread().setContextClassLoader(classloader); } } public HtmlEmail createEmail(T report) throws MalformedURLException, EmailException { HtmlEmail email = new HtmlEmail(); setEmailSettings(email); addReportContent(email, report); return email; } public boolean areEmailSettingsSet() { return isNotBlank(emailSettings.getSmtpHost()); } protected abstract void addReportContent(HtmlEmail email, T report) throws EmailException, MalformedURLException; private void setEmailSettings(MultiPartEmail email) throws EmailException { configureSecureConnection(email); email.setHostName(emailSettings.getSmtpHost()); email.setSocketConnectionTimeout(SOCKET_TIMEOUT); email.setSocketTimeout(SOCKET_TIMEOUT); email.setCharset(UTF_8.name()); email.setFrom(emailSettings.getFrom(), emailSettings.getFromName()); if (isNotBlank(emailSettings.getSmtpUsername() + emailSettings.getSmtpPassword())) { email.setAuthentication(emailSettings.getSmtpUsername(), emailSettings.getSmtpPassword()); } } private void configureSecureConnection(MultiPartEmail email) { String secureConnection = emailSettings.getSecureConnection(); int smtpPort = emailSettings.getSmtpPort(); if (equalsIgnoreCase(secureConnection, "ssl")) { email.setSSLOnConnect(true); email.setSSLCheckServerIdentity(true); email.setSslSmtpPort(String.valueOf(smtpPort)); // 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(smtpPort); } else if (equalsIgnoreCase(secureConnection, "starttls")) { email.setStartTLSEnabled(true); email.setStartTLSRequired(true); email.setSSLCheckServerIdentity(true); email.setSmtpPort(smtpPort); } else if (isBlank(secureConnection)) { email.setSmtpPort(smtpPort); } else { throw new IllegalStateException("Unknown type of SMTP secure connection: " + secureConnection); } } }
4,153
36.423423
119
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/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.email; import javax.annotation.ParametersAreNonnullByDefault;
963
37.56
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/AnalysisIndexer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.util.Set; /** * Indexers that should be called when a project branch is analyzed */ public interface AnalysisIndexer { /** * This method is called when an analysis must be indexed. * * @param branchUuid UUID of a project or application branch */ void indexOnAnalysis(String branchUuid); /** * This method is called when an analysis must be indexed. * * @param branchUuid UUID of a project or application branch * @param unchangedComponentUuids UUIDs of components that didn't change in this analysis. * Indexers can be optimized by not re-indexing data related to these components. */ void indexOnAnalysis(String branchUuid, Set<String> unchangedComponentUuids); }
1,623
35.909091
114
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/BaseDoc.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Optional; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.elasticsearch.action.index.IndexRequest; import org.sonar.server.es.IndexType.IndexMainType; import org.sonar.server.es.IndexType.IndexRelationType; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static org.sonar.server.es.IndexType.FIELD_INDEX_TYPE; /** * Base implementation for business objects based on elasticsearch document */ public abstract class BaseDoc { private static final String SETPARENT_NOT_CALLED = "parent must be set on a doc associated to a IndexRelationType (see BaseDoc#setParent(String))"; private final IndexType indexType; private String parentId = null; protected final Map<String, Object> fields; protected BaseDoc(IndexType indexType) { this(indexType, new HashMap<>()); } protected BaseDoc(IndexType indexType, Map<String, Object> fields) { this.indexType = indexType; this.fields = fields; if (indexType instanceof IndexMainType mainType && mainType.getIndex().acceptsRelations()) { setField(mainType.getIndex().getJoinField(), Map.of("name", mainType.getType())); setField(FIELD_INDEX_TYPE, mainType.getType()); } } protected void setParent(String parentId) { checkState(this.indexType instanceof IndexRelationType, "Doc must be associated to a IndexRelationType to set a parent"); checkArgument(parentId != null && !parentId.isEmpty(), "parentId can't be null nor empty"); this.parentId = parentId; IndexRelationType indexRelationType = (IndexRelationType) this.indexType; setField(indexRelationType.getMainType().getIndex().getJoinField(), Map.of("name", indexRelationType.getName(), "parent", parentId)); setField(FIELD_INDEX_TYPE, indexRelationType.getName()); } public abstract String getId(); public Optional<String> getRouting() { // when using relations, routing MUST be defined and MUST be the id of the parent if (this.indexType instanceof IndexRelationType) { ensureSetParentCalled(); return Optional.of(this.parentId); } if (this.indexType instanceof IndexMainType && indexType.getMainType().getIndex().acceptsRelations()) { return Optional.of(getId()); } return getSimpleMainTypeRouting(); } /** * Intended to be overridden by subclass which wants to define a routing and which indexType is a {@link IndexMainType} * (if not a {@link IndexMainType}, this method will never be called). */ protected Optional<String> getSimpleMainTypeRouting() { return Optional.empty(); } /** * Use this method when field value can be null. See warning in {@link #getField(String)} */ @CheckForNull public <K> K getNullableField(String key) { if (!fields.containsKey(key)) { throw new IllegalStateException(String.format("Field %s not specified in query options", key)); } return (K) fields.get(key); } @CheckForNull public Date getNullableFieldAsDate(String key) { Object val = getNullableField(key); if (val != null) { if (val instanceof Date date) { return date; } if (val instanceof Number number) { return epochSecondsToDate(number); } return EsUtils.parseDateTime((String) val); } return null; } /** * Use this method when you are sure that the value can't be null in ES document. * <p/> * Warning with numbers - even if mapping declares long field, value can be an Integer * instead of an expected Long. The reason is that ES delegates the deserialization of JSON * to Jackson, which doesn't know the field type declared in mapping. See * https://groups.google.com/forum/#!searchin/elasticsearch/getsource$20integer$20long/elasticsearch/jxIY22TmA8U/PyqZPPyYQ0gJ * for more details. Workaround is to cast to java.lang.Number and then to call {@link Number#longValue()} */ public <K> K getField(String key) { K value = getNullableField(key); if (value == null) { throw new IllegalStateException("Value of index field is null: " + key); } return value; } public Date getFieldAsDate(String key) { Object value = getField(key); if (value instanceof Date date) { return date; } if (value instanceof Number number) { return epochSecondsToDate(number); } return EsUtils.parseDateTime((String) value); } public void setField(String key, @Nullable Object value) { fields.put(key, value); } public final Map<String, Object> getFields() { if (indexType instanceof IndexRelationType) { ensureSetParentCalled(); } return fields; } private void ensureSetParentCalled() { checkState(this.parentId != null, SETPARENT_NOT_CALLED); } public IndexRequest toIndexRequest() { IndexMainType mainType = this.indexType.getMainType(); return new IndexRequest(mainType.getIndex().getName()) .id(getId()) .routing(getRouting().orElse(null)) .source(getFields()); } private static Date epochSecondsToDate(Number value) { return new Date(value.longValue() * 1000L); } }
6,148
34.75
149
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/BulkIndexer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.LinkedHashMultiset; import com.google.common.collect.Multiset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import org.elasticsearch.action.DocWriteRequest; import org.elasticsearch.action.admin.indices.forcemerge.ForceMergeRequest; import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest; import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse; import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsRequest; import org.elasticsearch.action.bulk.BackoffPolicy; import org.elasticsearch.action.bulk.BulkItemResponse; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.bulk.BulkProcessor.Listener; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.ClearScrollRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchScrollRequest; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.common.document.DocumentField; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.core.TimeValue; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.sort.SortOrder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.utils.log.Profiler; import org.sonar.core.util.ProgressLogger; import static java.lang.String.format; /** * Helper to bulk requests in an efficient way : * <ul> * <li>bulk request is sent on the wire when its size is higher than 5Mb</li> * <li>on large table indexing, replicas and automatic refresh can be temporarily disabled</li> * </ul> */ public class BulkIndexer { private static final Logger LOGGER = LoggerFactory.getLogger(BulkIndexer.class); private static final ByteSizeValue FLUSH_BYTE_SIZE = new ByteSizeValue(1, ByteSizeUnit.MB); private static final int FLUSH_ACTIONS = -1; private static final String REFRESH_INTERVAL_SETTING = "index.refresh_interval"; private static final int DEFAULT_NUMBER_OF_SHARDS = 5; private final EsClient esClient; private final IndexType indexType; private final BulkProcessor bulkProcessor; private final IndexingResult result = new IndexingResult(); private final IndexingListener indexingListener; private final SizeHandler sizeHandler; public BulkIndexer(EsClient client, IndexType indexType, Size size) { this(client, indexType, size, IndexingListener.FAIL_ON_ERROR); } public BulkIndexer(EsClient client, IndexType indexType, Size size, IndexingListener indexingListener) { this.esClient = client; this.indexType = indexType; this.sizeHandler = size.createHandler(Runtime2.INSTANCE); this.indexingListener = indexingListener; BulkProcessorListener bulkProcessorListener = new BulkProcessorListener(); this.bulkProcessor = BulkProcessor.builder( client::bulkAsync, bulkProcessorListener) .setBackoffPolicy(BackoffPolicy.exponentialBackoff()) .setBulkSize(FLUSH_BYTE_SIZE) .setBulkActions(FLUSH_ACTIONS) .setConcurrentRequests(sizeHandler.getConcurrentRequests()) .build(); } public IndexType getIndexType() { return indexType; } public void start() { result.clear(); sizeHandler.beforeStart(this); } /** * @return the number of documents successfully indexed */ public IndexingResult stop() { try { bulkProcessor.awaitClose(1, TimeUnit.MINUTES); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("Elasticsearch bulk requests still being executed after 1 minute", e); } esClient.refresh(indexType.getMainType().getIndex()); sizeHandler.afterStop(this); indexingListener.onFinish(result); return result; } public void add(IndexRequest request) { result.incrementRequests(); bulkProcessor.add(request); } public void add(DeleteRequest request) { result.incrementRequests(); bulkProcessor.add(request); } public void add(DocWriteRequest request) { result.incrementRequests(); bulkProcessor.add(request); } public void addDeletion(SearchRequest searchRequest) { // TODO to be replaced by delete_by_query that is back in ES5 searchRequest .scroll(TimeValue.timeValueMinutes(5)) .source() .sort("_doc", SortOrder.ASC) .size(100) // load only doc ids, not _source fields .fetchSource(false); // this search is synchronous. An optimization would be to be non-blocking, // but it requires to tracking pending requests in close(). // Same semaphore can't be reused because of potential deadlock (requires to acquire // two locks) SearchResponse searchResponse = esClient.search(searchRequest); while (true) { SearchHit[] hits = searchResponse.getHits().getHits(); for (SearchHit hit : hits) { DocumentField routing = hit.field("_routing"); DeleteRequest deleteRequest = new DeleteRequest(hit.getIndex(), hit.getType(), hit.getId()); if (routing != null) { deleteRequest.routing(routing.getValue()); } add(deleteRequest); } String scrollId = searchResponse.getScrollId(); if (scrollId == null) { break; } searchResponse = esClient.scroll(new SearchScrollRequest(scrollId).scroll(TimeValue.timeValueMinutes(5))); if (hits.length == 0) { ClearScrollRequest clearScrollRequest = new ClearScrollRequest(); clearScrollRequest.addScrollId(scrollId); esClient.clearScroll(clearScrollRequest); break; } } } public void addDeletion(IndexType indexType, String id) { add(new DeleteRequest(indexType.getMainType().getIndex().getName()) .id(id)); } public void addDeletion(IndexType indexType, String id, @Nullable String routing) { add(new DeleteRequest(indexType.getMainType().getIndex().getName()) .id(id) .routing(routing)); } /** * Delete all the documents matching the given search request. This method is blocking. * Index is refreshed, so docs are not searchable as soon as method is executed. * <p> * Note that the parameter indexType could be removed if progress logs are not needed. */ public static IndexingResult delete(EsClient client, IndexType indexType, SearchRequest searchRequest) { BulkIndexer bulk = new BulkIndexer(client, indexType, Size.REGULAR); bulk.start(); bulk.addDeletion(searchRequest); return bulk.stop(); } private final class BulkProcessorListener implements Listener { private final Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER); @Override public void beforeBulk(long executionId, BulkRequest request) { profiler.start(); } @Override public void afterBulk(long executionId, BulkRequest request, BulkResponse response) { stopProfiler(request); List<DocId> successDocIds = new ArrayList<>(); for (BulkItemResponse item : response.getItems()) { if (item.isFailed()) { LOGGER.error("index [{}], type [{}], id [{}], message [{}]", item.getIndex(), item.getType(), item.getId(), item.getFailureMessage()); } else { result.incrementSuccess(); successDocIds.add(new DocId(item.getIndex(), item.getType(), item.getId())); } } indexingListener.onSuccess(successDocIds); } @Override public void afterBulk(long executionId, BulkRequest request, Throwable e) { LOGGER.error("Fail to execute bulk index request: " + request, e); stopProfiler(request); } private void stopProfiler(BulkRequest request) { if (profiler.isTraceEnabled()) { profiler.stopTrace(toString(request)); } } private String toString(BulkRequest bulkRequest) { StringBuilder message = new StringBuilder(); message.append("Bulk["); Multiset<BulkRequestKey> groupedRequests = LinkedHashMultiset.create(); for (int i = 0; i < bulkRequest.requests().size(); i++) { DocWriteRequest item = bulkRequest.requests().get(i); String requestType; if (item instanceof IndexRequest) { requestType = "index"; } else if (item instanceof UpdateRequest) { requestType = "update"; } else if (item instanceof DeleteRequest) { requestType = "delete"; } else { // Cannot happen, not allowed by BulkRequest's contract throw new IllegalStateException("Unsupported bulk request type: " + item.getClass()); } groupedRequests.add(new BulkRequestKey(requestType, item.index(), item.type())); } Set<Multiset.Entry<BulkRequestKey>> entrySet = groupedRequests.entrySet(); int size = entrySet.size(); int current = 0; for (Multiset.Entry<BulkRequestKey> requestEntry : entrySet) { message.append(requestEntry.getCount()).append(" ").append(requestEntry.getElement().toString()); current++; if (current < size) { message.append(", "); } } message.append("]"); return message.toString(); } } private static class BulkRequestKey { private String requestType; private String index; private String docType; private BulkRequestKey(String requestType, String index, String docType) { this.requestType = requestType; this.index = index; this.docType = docType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BulkRequestKey that = (BulkRequestKey) o; return Objects.equals(docType, that.docType) && Objects.equals(index, that.index) && Objects.equals(requestType, that.requestType); } @Override public int hashCode() { return Objects.hash(requestType, index, docType); } @Override public String toString() { return String.format("%s requests on %s/%s", requestType, index, docType); } } public enum Size { /** * Use this size for a limited number of documents. */ REGULAR { @Override SizeHandler createHandler(Runtime2 runtime2) { return new SizeHandler(); } }, /** * Large indexing is an heavy operation that populates an index generally from scratch. Replicas and * automatic refresh are disabled during bulk indexing and lucene segments are optimized at the end. * Use this size for initial indexing and if you expect unusual huge numbers of documents. */ LARGE { @Override SizeHandler createHandler(Runtime2 runtime2) { return new LargeSizeHandler(runtime2); } }; abstract SizeHandler createHandler(Runtime2 runtime2); } @VisibleForTesting static class Runtime2 { private static final Runtime2 INSTANCE = new Runtime2(); int getCores() { return Runtime.getRuntime().availableProcessors(); } } static class SizeHandler { /** * @see BulkProcessor.Builder#setConcurrentRequests(int) */ int getConcurrentRequests() { // in the same thread by default return 0; } void beforeStart(BulkIndexer bulkIndexer) { // nothing to do, to be overridden if needed } void afterStop(BulkIndexer bulkIndexer) { // nothing to do, to be overridden if needed } } static class LargeSizeHandler extends SizeHandler { private final Map<String, Object> initialSettings = new HashMap<>(); private final Runtime2 runtime2; private ProgressLogger progress; LargeSizeHandler(Runtime2 runtime2) { this.runtime2 = runtime2; } @Override int getConcurrentRequests() { // see SONAR-8075 int cores = runtime2.getCores(); // FIXME do not use DEFAULT_NUMBER_OF_SHARDS return Math.max(1, cores / DEFAULT_NUMBER_OF_SHARDS) - 1; } @Override void beforeStart(BulkIndexer bulkIndexer) { String index = bulkIndexer.indexType.getMainType().getIndex().getName(); this.progress = new ProgressLogger(format("Progress[BulkIndexer[%s]]", index), bulkIndexer.result.total, LOGGER) .setPluralLabel("requests"); this.progress.start(); Map<String, Object> temporarySettings = new HashMap<>(); GetSettingsResponse settingsResp = bulkIndexer.esClient.getSettings(new GetSettingsRequest()); // deactivate replicas int initialReplicas = Integer.parseInt(settingsResp.getSetting(index, IndexMetadata.SETTING_NUMBER_OF_REPLICAS)); if (initialReplicas > 0) { initialSettings.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, initialReplicas); temporarySettings.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0); } // deactivate periodical refresh String refreshInterval = settingsResp.getSetting(index, REFRESH_INTERVAL_SETTING); initialSettings.put(REFRESH_INTERVAL_SETTING, refreshInterval); temporarySettings.put(REFRESH_INTERVAL_SETTING, "-1"); updateSettings(bulkIndexer, temporarySettings); } @Override void afterStop(BulkIndexer bulkIndexer) { // optimize lucene segments and revert index settings // Optimization must be done before re-applying replicas: // http://www.elasticsearch.org/blog/performance-considerations-elasticsearch-indexing/ bulkIndexer.esClient.forcemerge(new ForceMergeRequest(bulkIndexer.indexType.getMainType().getIndex().getName())); updateSettings(bulkIndexer, initialSettings); this.progress.stop(); } private static void updateSettings(BulkIndexer bulkIndexer, Map<String, Object> settings) { UpdateSettingsRequest req = new UpdateSettingsRequest(bulkIndexer.indexType.getMainType().getIndex().getName()); req.settings(settings); bulkIndexer.esClient.putSettings(req); } } }
15,408
34.504608
144
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/DocId.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import javax.annotation.concurrent.Immutable; import static java.util.Objects.requireNonNull; @Immutable class DocId { private final String index; private final String indexType; private final String id; DocId(String index, String indexType, String id) { this.index = requireNonNull(index, "index can't be null"); this.indexType = requireNonNull(indexType,"type can't be null"); this.id = requireNonNull(id, "id can't be null"); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DocId docId = (DocId) o; return index.equals(docId.index) && indexType.equals(docId.indexType) && id.equals(docId.id); } @Override public int hashCode() { int result = index.hashCode(); result = 31 * result + indexType.hashCode(); result = 31 * result + id.hashCode(); return result; } @Override public String toString() { return "DocId{" + index + '/' + indexType + '/' + id + '}'; } }
1,934
28.769231
97
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/ElasticsearchException.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; public class ElasticsearchException extends RuntimeException { public ElasticsearchException(String message, Throwable cause) { super(message, cause); } }
1,037
36.071429
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/EsClient.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import com.google.common.collect.Lists; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.util.Arrays; import java.util.function.Supplier; import javax.annotation.Nullable; import javax.net.ssl.SSLContext; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContexts; import org.apache.http.util.EntityUtils; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheRequest; import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheResponse; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.admin.indices.forcemerge.ForceMergeRequest; import org.elasticsearch.action.admin.indices.forcemerge.ForceMergeResponse; import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; import org.elasticsearch.action.admin.indices.refresh.RefreshResponse; import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest; import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse; import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsRequest; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.ClearScrollRequest; import org.elasticsearch.action.search.ClearScrollResponse; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchScrollRequest; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.client.Cancellable; import org.elasticsearch.client.Request; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.Requests; import org.elasticsearch.client.Response; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.CreateIndexResponse; import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.client.indices.GetIndexResponse; import org.elasticsearch.client.indices.GetMappingsRequest; import org.elasticsearch.client.indices.GetMappingsResponse; import org.elasticsearch.client.indices.PutMappingRequest; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.elasticsearch.common.Priority; import org.jetbrains.annotations.NotNull; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.api.utils.log.Profiler; import org.sonar.server.es.response.ClusterStatsResponse; import org.sonar.server.es.response.IndicesStatsResponse; import org.sonar.server.es.response.NodeStatsResponse; import static org.sonar.server.es.EsRequestDetails.computeDetailsAsString; /** * Wrapper to connect to Elasticsearch node. Handles correctly errors (logging + exceptions * with context) and profiling of requests. */ public class EsClient implements Closeable { public static final Logger LOGGER = Loggers.get("es"); private static final String ES_USERNAME = "elastic"; private final RestHighLevelClient restHighLevelClient; private final Gson gson; public EsClient(HttpHost... hosts) { this(new MinimalRestHighLevelClient(null, null, null, hosts)); } public EsClient(@Nullable String searchPassword, @Nullable String keyStorePath, @Nullable String keyStorePassword, HttpHost... hosts) { this(new MinimalRestHighLevelClient(searchPassword, keyStorePath, keyStorePassword, hosts)); } EsClient(RestHighLevelClient restHighLevelClient) { this.restHighLevelClient = restHighLevelClient; this.gson = new GsonBuilder().create(); } public BulkResponse bulk(BulkRequest bulkRequest) { return execute(() -> restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT)); } public Cancellable bulkAsync(BulkRequest bulkRequest, ActionListener<BulkResponse> listener) { return restHighLevelClient.bulkAsync(bulkRequest, RequestOptions.DEFAULT, listener); } public static SearchRequest prepareSearch(String indexName) { return Requests.searchRequest(indexName); } public static SearchRequest prepareSearch(IndexType.IndexMainType mainType) { return Requests.searchRequest(mainType.getIndex().getName()); } public SearchResponse search(SearchRequest searchRequest) { return execute(() -> restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT), () -> computeDetailsAsString(searchRequest)); } public SearchResponse scroll(SearchScrollRequest searchScrollRequest) { return execute(() -> restHighLevelClient.scroll(searchScrollRequest, RequestOptions.DEFAULT), () -> computeDetailsAsString(searchScrollRequest)); } public ClearScrollResponse clearScroll(ClearScrollRequest clearScrollRequest) { return execute(() -> restHighLevelClient.clearScroll(clearScrollRequest, RequestOptions.DEFAULT)); } public DeleteResponse delete(DeleteRequest deleteRequest) { return execute(() -> restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT), () -> computeDetailsAsString(deleteRequest)); } public RefreshResponse refresh(Index... indices) { RefreshRequest refreshRequest = new RefreshRequest() .indices(Arrays.stream(indices).map(Index::getName).toArray(String[]::new)); return execute(() -> restHighLevelClient.indices().refresh(refreshRequest, RequestOptions.DEFAULT), () -> computeDetailsAsString(refreshRequest)); } public ForceMergeResponse forcemerge(ForceMergeRequest forceMergeRequest) { return execute(() -> restHighLevelClient.indices().forcemerge(forceMergeRequest, RequestOptions.DEFAULT)); } public AcknowledgedResponse putSettings(UpdateSettingsRequest req) { return execute(() -> restHighLevelClient.indices().putSettings(req, RequestOptions.DEFAULT)); } public ClearIndicesCacheResponse clearCache(ClearIndicesCacheRequest request) { return execute(() -> restHighLevelClient.indices().clearCache(request, RequestOptions.DEFAULT), () -> computeDetailsAsString(request)); } public IndexResponse index(IndexRequest indexRequest) { return execute(() -> restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT), () -> computeDetailsAsString(indexRequest)); } public GetResponse get(GetRequest request) { return execute(() -> restHighLevelClient.get(request, RequestOptions.DEFAULT), () -> computeDetailsAsString(request)); } public GetIndexResponse getIndex(GetIndexRequest getRequest) { return execute(() -> restHighLevelClient.indices().get(getRequest, RequestOptions.DEFAULT)); } public boolean indexExists(GetIndexRequest getIndexRequest) { return execute(() -> restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT), () -> computeDetailsAsString(getIndexRequest)); } public CreateIndexResponse create(CreateIndexRequest createIndexRequest) { return execute(() -> restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT), () -> computeDetailsAsString(createIndexRequest)); } public AcknowledgedResponse deleteIndex(DeleteIndexRequest deleteIndexRequest) { return execute(() -> restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT)); } public AcknowledgedResponse putMapping(PutMappingRequest request) { return execute(() -> restHighLevelClient.indices().putMapping(request, RequestOptions.DEFAULT), () -> computeDetailsAsString(request)); } public ClusterHealthResponse clusterHealth(ClusterHealthRequest clusterHealthRequest) { return execute(() -> restHighLevelClient.cluster().health(clusterHealthRequest, RequestOptions.DEFAULT), () -> computeDetailsAsString(clusterHealthRequest)); } public void waitForStatus(ClusterHealthStatus clusterHealthStatus) { clusterHealth(new ClusterHealthRequest().waitForEvents(Priority.LANGUID).waitForStatus(clusterHealthStatus)); } // https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-stats.html public NodeStatsResponse nodesStats() { return execute(() -> { Request request = new Request("GET", "/_nodes/stats/fs,process,jvm,indices,breaker"); Response response = restHighLevelClient.getLowLevelClient().performRequest(request); return NodeStatsResponse.toNodeStatsResponse(gson.fromJson(EntityUtils.toString(response.getEntity()), JsonObject.class)); }); } // https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-stats.html public IndicesStatsResponse indicesStats(String... indices) { return execute(() -> { Request request = new Request("GET", "/" + (indices.length > 0 ? (String.join(",", indices) + "/") : "") + "_stats"); request.addParameter("level", "shards"); Response response = restHighLevelClient.getLowLevelClient().performRequest(request); return IndicesStatsResponse.toIndicesStatsResponse(gson.fromJson(EntityUtils.toString(response.getEntity()), JsonObject.class)); }, () -> computeDetailsAsString(indices)); } // https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-stats.html public ClusterStatsResponse clusterStats() { return execute(() -> { Request request = new Request("GET", "/_cluster/stats"); Response response = restHighLevelClient.getLowLevelClient().performRequest(request); return ClusterStatsResponse.toClusterStatsResponse(gson.fromJson(EntityUtils.toString(response.getEntity()), JsonObject.class)); }); } public GetSettingsResponse getSettings(GetSettingsRequest getSettingsRequest) { return execute(() -> restHighLevelClient.indices().getSettings(getSettingsRequest, RequestOptions.DEFAULT)); } public GetMappingsResponse getMapping(GetMappingsRequest getMappingsRequest) { return execute(() -> restHighLevelClient.indices().getMapping(getMappingsRequest, RequestOptions.DEFAULT)); } @Override public void close() { try { restHighLevelClient.close(); } catch (IOException e) { throw new ElasticsearchException("Could not close ES Rest high level client", e); } } /** * Internal usage only * * @return native ES client object */ RestHighLevelClient nativeClient() { return restHighLevelClient; } static class MinimalRestHighLevelClient extends RestHighLevelClient { private static final int CONNECT_TIMEOUT = 5000; private static final int SOCKET_TIMEOUT = 60000; public MinimalRestHighLevelClient(@Nullable String searchPassword, @Nullable String keyStorePath, @Nullable String keyStorePassword, HttpHost... hosts) { super(buildHttpClient(searchPassword, keyStorePath, keyStorePassword, hosts).build(), RestClient::close, Lists.newArrayList(), true); } MinimalRestHighLevelClient(RestClient restClient) { super(restClient, RestClient::close, Lists.newArrayList(), true); } @NotNull private static RestClientBuilder buildHttpClient(@Nullable String searchPassword, @Nullable String keyStorePath, @Nullable String keyStorePassword, HttpHost[] hosts) { return RestClient.builder(hosts) .setRequestConfigCallback(r -> r .setConnectTimeout(CONNECT_TIMEOUT) .setSocketTimeout(SOCKET_TIMEOUT)) .setHttpClientConfigCallback(httpClientBuilder -> { if (searchPassword != null) { BasicCredentialsProvider provider = getBasicCredentialsProvider(searchPassword); httpClientBuilder.setDefaultCredentialsProvider(provider); } if (keyStorePath != null) { SSLContext sslContext = getSSLContext(keyStorePath, keyStorePassword); httpClientBuilder.setSSLContext(sslContext); } return httpClientBuilder; }); } private static BasicCredentialsProvider getBasicCredentialsProvider(String searchPassword) { BasicCredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(ES_USERNAME, searchPassword)); return provider; } private static SSLContext getSSLContext(String keyStorePath, @Nullable String keyStorePassword) { try { KeyStore keyStore = KeyStore.getInstance("pkcs12"); try (InputStream is = Files.newInputStream(Paths.get(keyStorePath))) { keyStore.load(is, keyStorePassword == null ? null : keyStorePassword.toCharArray()); } SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(keyStore, null); return sslBuilder.build(); } catch (IOException | GeneralSecurityException e) { throw new IllegalStateException("Failed to setup SSL context on ES client", e); } } } <R> R execute(EsRequestExecutor<R> executor) { return execute(executor, () -> ""); } <R> R execute(EsRequestExecutor<R> executor, Supplier<String> requestDetails) { Profiler profiler = Profiler.createIfTrace(EsClient.LOGGER).start(); try { return executor.execute(); } catch (Exception e) { throw new ElasticsearchException("Fail to execute es request" + requestDetails.get(), e); } finally { if (profiler.isTraceEnabled()) { profiler.stopTrace(requestDetails.get()); } } } @FunctionalInterface interface EsRequestExecutor<R> { R execute() throws IOException; } }
15,445
43.131429
139
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/EsClientProvider.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import com.google.common.net.HostAndPort; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.apache.http.HttpHost; import org.elasticsearch.common.settings.Settings; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.config.Configuration; import org.sonar.api.server.ServerSide; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.process.cluster.NodeType; import org.springframework.context.annotation.Bean; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_HTTP_KEYSTORE; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_HTTP_KEYSTORE_PASSWORD; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NAME; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_TYPE; import static org.sonar.process.ProcessProperties.Property.CLUSTER_SEARCH_HOSTS; import static org.sonar.process.ProcessProperties.Property.CLUSTER_SEARCH_PASSWORD; import static org.sonar.process.ProcessProperties.Property.SEARCH_HOST; import static org.sonar.process.ProcessProperties.Property.SEARCH_PORT; import static org.sonar.process.cluster.NodeType.SEARCH; @ComputeEngineSide @ServerSide public class EsClientProvider { private static final Logger LOGGER = LoggerFactory.getLogger(EsClientProvider.class); @Bean("EsClient") public EsClient provide(Configuration config) { Settings.Builder esSettings = Settings.builder(); // mandatory property defined by bootstrap process esSettings.put("cluster.name", config.get(CLUSTER_NAME.getKey()).get()); boolean clusterEnabled = config.getBoolean(CLUSTER_ENABLED.getKey()).orElse(false); boolean searchNode = !clusterEnabled || SEARCH.equals(NodeType.parse(config.get(CLUSTER_NODE_TYPE.getKey()).orElse(null))); List<HttpHost> httpHosts; if (clusterEnabled && !searchNode) { httpHosts = getHttpHosts(config); LOGGER.info("Connected to remote Elasticsearch: [{}]", displayedAddresses(httpHosts)); } else { // defaults provided in: // * in org.sonar.process.ProcessProperties.Property.SEARCH_HOST // * in org.sonar.process.ProcessProperties.Property.SEARCH_PORT HostAndPort host = HostAndPort.fromParts(config.get(SEARCH_HOST.getKey()).get(), config.getInt(SEARCH_PORT.getKey()).get()); httpHosts = Collections.singletonList(toHttpHost(host, config)); LOGGER.info("Connected to local Elasticsearch: [{}]", displayedAddresses(httpHosts)); } return new EsClient(config.get(CLUSTER_SEARCH_PASSWORD.getKey()).orElse(null), config.get(CLUSTER_ES_HTTP_KEYSTORE.getKey()).orElse(null), config.get(CLUSTER_ES_HTTP_KEYSTORE_PASSWORD.getKey()).orElse(null), httpHosts.toArray(new HttpHost[0])); } private static List<HttpHost> getHttpHosts(Configuration config) { return Arrays.stream(config.getStringArray(CLUSTER_SEARCH_HOSTS.getKey())) .map(HostAndPort::fromString) .map(host -> toHttpHost(host, config)) .toList(); } private static HttpHost toHttpHost(HostAndPort host, Configuration config) { try { String scheme = config.get(CLUSTER_ES_HTTP_KEYSTORE.getKey()).isPresent() ? "https" : HttpHost.DEFAULT_SCHEME_NAME; return new HttpHost(InetAddress.getByName(host.getHost()), host.getPortOrDefault(9001), scheme); } catch (UnknownHostException e) { throw new IllegalStateException("Can not resolve host [" + host + "]", e); } } private static String displayedAddresses(List<HttpHost> httpHosts) { return httpHosts.stream().map(HttpHost::toString).collect(Collectors.joining(", ")); } }
4,684
44.048077
130
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/EsModule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import org.sonar.core.platform.Module; public class EsModule extends Module { @Override protected void configureModule() { add(new EsClientProvider()); } }
1,040
33.7
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/EsRequestDetails.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.util.Arrays; import org.apache.commons.lang.StringUtils; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheRequest; import org.elasticsearch.client.indices.PutMappingRequest; import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchScrollRequest; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.common.bytes.BytesReference; final class EsRequestDetails { private static final String ON_INDICES_MESSAGE = " on indices '%s'"; private EsRequestDetails() { // this is utility class only } static String computeDetailsAsString(SearchRequest searchRequest) { StringBuilder message = new StringBuilder(); message.append(String.format("ES search request '%s'", searchRequest)); if (searchRequest.indices().length > 0) { message.append(String.format(ON_INDICES_MESSAGE, Arrays.toString(searchRequest.indices()))); } return message.toString(); } public static String computeDetailsAsString(SearchScrollRequest searchScrollRequest) { return String.format("ES search scroll request for scroll id '%s'", searchScrollRequest.scroll()); } static String computeDetailsAsString(DeleteRequest deleteRequest) { return new StringBuilder() .append("ES delete request of doc ") .append(deleteRequest.id()) .append(" in index ") .append(deleteRequest.index()) .toString(); } static String computeDetailsAsString(RefreshRequest refreshRequest) { StringBuilder message = new StringBuilder(); message.append("ES refresh request"); if (refreshRequest.indices().length > 0) { message.append(String.format(ON_INDICES_MESSAGE, StringUtils.join(refreshRequest.indices(), ","))); } return message.toString(); } static String computeDetailsAsString(ClearIndicesCacheRequest request) { StringBuilder message = new StringBuilder(); message.append("ES clear cache request"); if (request.indices().length > 0) { message.append(String.format(ON_INDICES_MESSAGE, StringUtils.join(request.indices(), ","))); } String[] fields = request.fields(); if (fields != null && fields.length > 0) { message.append(String.format(" on fields '%s'", StringUtils.join(fields, ","))); } if (request.queryCache()) { message.append(" with filter cache"); } if (request.fieldDataCache()) { message.append(" with field data cache"); } if (request.requestCache()) { message.append(" with request cache"); } return message.toString(); } static String computeDetailsAsString(IndexRequest indexRequest) { return new StringBuilder().append("ES index request") .append(String.format(" for key '%s'", indexRequest.id())) .append(String.format(" on index '%s'", indexRequest.index())) .toString(); } static String computeDetailsAsString(GetRequest request) { return new StringBuilder().append("ES get request") .append(String.format(" for key '%s'", request.id())) .append(String.format(" on index '%s'", request.index())) .toString(); } static String computeDetailsAsString(GetIndexRequest getIndexRequest) { StringBuilder message = new StringBuilder(); message.append("ES indices exists request"); if (getIndexRequest.indices().length > 0) { message.append(String.format(ON_INDICES_MESSAGE, StringUtils.join(getIndexRequest.indices(), ","))); } return message.toString(); } static String computeDetailsAsString(CreateIndexRequest createIndexRequest) { return String.format("ES create index '%s'", createIndexRequest.index()); } static String computeDetailsAsString(PutMappingRequest request) { StringBuilder message = new StringBuilder(); message.append("ES put mapping request"); if (request.indices().length > 0) { message.append(String.format(ON_INDICES_MESSAGE, StringUtils.join(request.indices(), ","))); } BytesReference source = request.source(); if (source != null) { message.append(String.format(" with source '%s'", source.utf8ToString())); } return message.toString(); } static String computeDetailsAsString(ClusterHealthRequest clusterHealthRequest) { StringBuilder message = new StringBuilder(); message.append("ES cluster health request"); String[] indices = clusterHealthRequest.indices(); if (indices != null && indices.length > 0) { message.append(String.format(ON_INDICES_MESSAGE, StringUtils.join(indices, ","))); } return message.toString(); } static String computeDetailsAsString(String... indices) { StringBuilder message = new StringBuilder(); message.append("ES indices stats request"); if (indices.length > 0) { message.append(String.format(ON_INDICES_MESSAGE, StringUtils.join(indices, ","))); } return message.toString(); } }
6,157
37.974684
106
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/EsUtils.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Queue; import java.util.function.Function; import java.util.regex.Pattern; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchScrollRequest; import org.elasticsearch.core.TimeValue; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.SortOrder; import org.joda.time.format.ISODateTimeFormat; public class EsUtils { public static final int SCROLL_TIME_IN_MINUTES = 3; /** * See https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-regexp-query.html */ private static final Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[#@&~<>\"{}()\\[\\].+*?^$\\\\|]"); private EsUtils() { // only static methods } public static <D extends BaseDoc> List<D> convertToDocs(SearchHits hits, Function<Map<String, Object>, D> converter) { List<D> docs = new ArrayList<>(); for (SearchHit hit : hits.getHits()) { docs.add(converter.apply(hit.getSourceAsMap())); } return docs; } public static Map<String, Long> termsToMap(Terms terms) { LinkedHashMap<String, Long> map = new LinkedHashMap<>(); List<? extends Terms.Bucket> buckets = terms.getBuckets(); for (Terms.Bucket bucket : buckets) { map.put(bucket.getKeyAsString(), bucket.getDocCount()); } return map; } public static List<String> termsKeys(Terms terms) { terms.getBuckets(); return terms.getBuckets() .stream() .map(Terms.Bucket::getKeyAsString) .toList(); } @CheckForNull public static Date parseDateTime(@Nullable String s) { if (s == null) { return null; } return ISODateTimeFormat.dateTime().parseDateTime(s).toDate(); } @CheckForNull public static String formatDateTime(@Nullable Date date) { if (date != null) { return ISODateTimeFormat.dateTime().print(date.getTime()); } return null; } /** * Optimize scolling, by specifying document sorting. * See https://www.elastic.co/guide/en/elasticsearch/reference/2.4/search-request-scroll.html#search-request-scroll */ public static void optimizeScrollRequest(SearchSourceBuilder esSearch) { esSearch.sort("_doc", SortOrder.ASC); } /** * Escapes regexp special characters so that text can be forwarded from end-user input * to Elasticsearch regexp query (for instance attributes "include" and "exclude" of * term aggregations. */ public static String escapeSpecialRegexChars(String str) { return SPECIAL_REGEX_CHARS.matcher(str).replaceAll("\\\\$0"); } public static <I> Iterator<I> scrollIds(EsClient esClient, SearchResponse scrollResponse, Function<String, I> idConverter) { return new IdScrollIterator<>(esClient, scrollResponse, idConverter); } private static class IdScrollIterator<I> implements Iterator<I> { private final EsClient esClient; private final String scrollId; private final Function<String, I> idConverter; private final Queue<SearchHit> hits = new ArrayDeque<>(); private IdScrollIterator(EsClient esClient, SearchResponse scrollResponse, Function<String, I> idConverter) { this.esClient = esClient; this.scrollId = scrollResponse.getScrollId(); this.idConverter = idConverter; Collections.addAll(hits, scrollResponse.getHits().getHits()); } @Override public boolean hasNext() { if (hits.isEmpty()) { SearchScrollRequest esRequest = new SearchScrollRequest(scrollId) .scroll(TimeValue.timeValueMinutes(SCROLL_TIME_IN_MINUTES)); Collections.addAll(hits, esClient.scroll(esRequest).getHits().getHits()); } return !hits.isEmpty(); } @Override public I next() { if (!hasNext()) { throw new NoSuchElementException(); } return idConverter.apply(hits.poll().getId()); } @Override public void remove() { throw new UnsupportedOperationException("Cannot remove item when scrolling"); } } }
5,360
32.50625
126
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/EventIndexer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.util.Collection; import org.sonar.db.DbSession; import org.sonar.db.es.EsQueueDto; /** * A {@link EventIndexer} populates an Elasticsearch index * based on events related to entities and branches. This interface allows to quickly integrate new * indices in the lifecycle of entities and branches. * * If the related index handles verification of authorization, * then the implementation of {@link EventIndexer} must * also implement {@link org.sonar.server.permission.index.NeedAuthorizationIndexer} */ public interface EventIndexer extends ResilientIndexer { Collection<EsQueueDto> prepareForRecoveryOnEntityEvent(DbSession dbSession, Collection<String> entityUuids, Indexers.EntityEvent cause); Collection<EsQueueDto> prepareForRecoveryOnBranchEvent(DbSession dbSession, Collection<String> branchUuids, Indexers.BranchEvent cause); }
1,736
41.365854
138
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/Facets.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.time.ZoneId; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.CheckForNull; import org.apache.commons.lang.builder.ReflectionToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.search.aggregations.Aggregation; import org.elasticsearch.search.aggregations.Aggregations; import org.elasticsearch.search.aggregations.HasAggregations; import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation; import org.elasticsearch.search.aggregations.bucket.filter.Filter; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.bucket.missing.Missing; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.metrics.Sum; import static org.sonar.api.utils.DateUtils.parseDateTime; import static org.sonarqube.ws.client.issue.IssuesWsParameters.FACET_MODE_EFFORT; public class Facets { public static final String SELECTED_SUB_AGG_NAME_SUFFIX = "_selected"; public static final String TOTAL = "total"; private static final String NO_DATA_PREFIX = "no_data_"; private static final String FILTER_SUFFIX = "_filter"; private static final String FILTER_BY_RULE_PREFIX = "filter_by_rule_types_"; private final LinkedHashMap<String, LinkedHashMap<String, Long>> facetsByName; private final ZoneId timeZone; public Facets(LinkedHashMap<String, LinkedHashMap<String, Long>> facetsByName, ZoneId timeZone) { this.facetsByName = facetsByName; this.timeZone = timeZone; } public Facets(SearchResponse response, ZoneId timeZone) { this.facetsByName = new LinkedHashMap<>(); this.timeZone = timeZone; Aggregations aggregations = response.getAggregations(); if (aggregations != null) { for (Aggregation facet : aggregations) { processAggregation(facet); } } } private void processAggregation(Aggregation aggregation) { if (Missing.class.isAssignableFrom(aggregation.getClass())) { processMissingAggregation((Missing) aggregation); } else if (Terms.class.isAssignableFrom(aggregation.getClass())) { processTermsAggregation((Terms) aggregation); } else if (Filter.class.isAssignableFrom(aggregation.getClass())) { processSubAggregations((Filter) aggregation); } else if (HasAggregations.class.isAssignableFrom(aggregation.getClass())) { processSubAggregations((HasAggregations) aggregation); } else if (Histogram.class.isAssignableFrom(aggregation.getClass())) { processDateHistogram((Histogram) aggregation); } else if (Sum.class.isAssignableFrom(aggregation.getClass())) { processSum((Sum) aggregation); } else if (MultiBucketsAggregation.class.isAssignableFrom(aggregation.getClass())) { processMultiBucketAggregation((MultiBucketsAggregation) aggregation); } else { throw new IllegalArgumentException("Aggregation type not supported yet: " + aggregation.getClass()); } } private void processMissingAggregation(Missing aggregation) { long docCount = aggregation.getDocCount(); if (docCount > 0L) { LinkedHashMap<String, Long> facet = getOrCreateFacet(aggregation.getName().replace("_missing", "")); if (aggregation.getAggregations().getAsMap().containsKey(FACET_MODE_EFFORT)) { facet.put("", Math.round(((Sum) aggregation.getAggregations().get(FACET_MODE_EFFORT)).getValue())); } else { facet.put("", docCount); } } } private void processTermsAggregation(Terms aggregation) { String facetName = aggregation.getName(); // TODO document this naming convention if (facetName.contains("__") && !facetName.startsWith("__")) { facetName = facetName.substring(0, facetName.indexOf("__")); } facetName = facetName.replace(SELECTED_SUB_AGG_NAME_SUFFIX, ""); LinkedHashMap<String, Long> facet = getOrCreateFacet(facetName); for (Terms.Bucket value : aggregation.getBuckets()) { List<Aggregation> aggregationList = value.getAggregations().asList(); if (aggregationList.size() == 1) { facet.put(value.getKeyAsString(), Math.round(((Sum) aggregationList.get(0)).getValue())); } else { facet.put(value.getKeyAsString(), value.getDocCount()); } } } private void processSubAggregations(HasAggregations aggregation) { if (Filter.class.isAssignableFrom(aggregation.getClass())) { Filter filter = (Filter) aggregation; if (filter.getName().startsWith(NO_DATA_PREFIX)) { LinkedHashMap<String, Long> facet = getOrCreateFacet(filter.getName().replaceFirst(NO_DATA_PREFIX, "")); facet.put("NO_DATA", ((Filter) aggregation).getDocCount()); } } for (Aggregation sub : getOrderedAggregations(aggregation)) { processAggregation(sub); } } private static List<Aggregation> getOrderedAggregations(HasAggregations topAggregation) { String topAggregationName = ((Aggregation) topAggregation).getName(); List<Aggregation> orderedAggregations = new ArrayList<>(); for (Aggregation aggregation : topAggregation.getAggregations()) { if (isNameMatchingTopAggregation(topAggregationName, aggregation.getName())) { orderedAggregations.add(0, aggregation); } else { orderedAggregations.add(aggregation); } } return orderedAggregations; } private static boolean isNameMatchingTopAggregation(String topAggregationName, String aggregationName) { return aggregationName.equals(topAggregationName) || aggregationName.equals(FILTER_BY_RULE_PREFIX + topAggregationName.replace(FILTER_SUFFIX, "")); } private void processDateHistogram(Histogram aggregation) { LinkedHashMap<String, Long> facet = getOrCreateFacet(aggregation.getName()); for (Histogram.Bucket value : aggregation.getBuckets()) { String day = dateTimeToDate(value.getKeyAsString(), timeZone); if (value.getAggregations().getAsMap().containsKey(FACET_MODE_EFFORT)) { facet.put(day, Math.round(((Sum) value.getAggregations().get(FACET_MODE_EFFORT)).getValue())); } else { facet.put(day, value.getDocCount()); } } } private static String dateTimeToDate(String timestamp, ZoneId timeZone) { Date date = parseDateTime(timestamp); return date.toInstant().atZone(timeZone).toLocalDate().toString(); } private void processSum(Sum aggregation) { getOrCreateFacet(aggregation.getName()).put(TOTAL, Math.round(aggregation.getValue())); } private void processMultiBucketAggregation(MultiBucketsAggregation aggregation) { LinkedHashMap<String, Long> facet = getOrCreateFacet(aggregation.getName()); aggregation.getBuckets().forEach(bucket -> facet.put(bucket.getKeyAsString(), bucket.getDocCount())); } public boolean contains(String facetName) { return facetsByName.containsKey(facetName); } /** * The buckets of the given facet. Null if the facet does not exist */ @CheckForNull public LinkedHashMap<String, Long> get(String facetName) { return facetsByName.get(facetName); } public Map<String, LinkedHashMap<String, Long>> getAll() { return facetsByName; } public Set<String> getBucketKeys(String facetName) { LinkedHashMap<String, Long> facet = facetsByName.get(facetName); if (facet != null) { return facet.keySet(); } return Collections.emptySet(); } public Set<String> getNames() { return facetsByName.keySet(); } @Override public String toString() { return ReflectionToStringBuilder.toString(this, ToStringStyle.SIMPLE_STYLE); } private LinkedHashMap<String, Long> getOrCreateFacet(String facetName) { return facetsByName.computeIfAbsent(facetName, n -> new LinkedHashMap<>()); } }
8,862
39.47032
112
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/Index.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.util.Objects; import org.apache.commons.lang.StringUtils; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; public final class Index { public static final Index ALL_INDICES = Index.simple("_all"); private final String name; private final boolean relations; private Index(String name, boolean acceptsRelations) { checkArgument(name != null && !name.isEmpty(), "Index name can't be null nor empty"); checkArgument("_all".equals(name) || StringUtils.isAllLowerCase(name), "Index name must be lower-case letters or '_all': %s", name); this.name = name; this.relations = acceptsRelations; } public static Index simple(String name) { return new Index(name, false); } public static Index withRelations(String name) { return new Index(name, true); } public String getName() { return name; } public boolean acceptsRelations() { return relations; } /** * @return the name of the join field for this index if it accepts relations * @throws IllegalStateException if index does not accept relations * @see #acceptsRelations() */ public String getJoinField() { checkState(relations, "Only index accepting relations has a join field"); return "join_" + name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Index index = (Index) o; return relations == index.relations && name.equals(index.name); } @Override public int hashCode() { return Objects.hash(name, relations); } @Override public String toString() { return "[" + name + (relations ? "|*" : "|") + ']'; } }
2,665
28.955056
136
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/IndexDefinition.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.util.HashMap; import java.util.Map; import org.sonar.api.server.ServerSide; import org.sonar.server.es.newindex.NewAuthorizedIndex; import org.sonar.server.es.newindex.NewIndex; import org.sonar.server.es.newindex.NewRegularIndex; import org.sonar.server.es.newindex.SettingsConfiguration; import static com.google.common.base.Preconditions.checkArgument; @ServerSide public interface IndexDefinition { class IndexDefinitionContext { private final Map<String, NewIndex> byKey = new HashMap<>(); public NewRegularIndex create(Index index, SettingsConfiguration settingsConfiguration) { String indexName = index.getName(); checkArgument(!byKey.containsKey(indexName), String.format("Index already exists: %s", indexName)); NewRegularIndex newIndex = new NewRegularIndex(index, settingsConfiguration); byKey.put(indexName, newIndex); return newIndex; } public NewAuthorizedIndex createWithAuthorization(Index index, SettingsConfiguration settingsConfiguration) { checkArgument(index.acceptsRelations(), "Index with authorization must accept relations"); String indexName = index.getName(); checkArgument(!byKey.containsKey(indexName), String.format("Index already exists: %s", indexName)); NewAuthorizedIndex newIndex = new NewAuthorizedIndex(index, settingsConfiguration); byKey.put(indexName, newIndex); return newIndex; } public Map<String, NewIndex> getIndices() { return byKey; } } void define(IndexDefinitionContext context); }
2,431
37
113
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/IndexDefinitionHash.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import com.google.common.collect.ImmutableSortedMap; import java.util.Arrays; import java.util.Map; import java.util.SortedMap; import java.util.function.Function; import java.util.stream.Collectors; import org.apache.commons.codec.digest.DigestUtils; import org.sonar.server.es.newindex.BuiltIndex; /** * Hash of index definition is stored in the index itself in order to detect changes of mappings * between SonarQube versions. In this case, contrary to database tables, indices are dropped * and re-populated from scratch. There's no attempt to migrate existing data. */ class IndexDefinitionHash { private static final char DELIMITER = ','; private IndexDefinitionHash() { } static String of(BuiltIndex<?> index) { IndexType.IndexMainType mainType = index.getMainType(); return of( index.getSettings().toString(), Map.of(mainType.getIndex(), mainType), index.getRelationTypes().stream().collect(Collectors.toMap(IndexType.IndexRelationType::getName, Function.identity())), index.getAttributes()); } private static String of(String str, Map<?, ?>... maps) { StringBuilder sb = new StringBuilder(str); for (Map<?, ?> map : maps) { appendMap(sb, map); } return DigestUtils.sha256Hex(sb.toString()); } private static void appendMap(StringBuilder sb, Map<?, ?> attributes) { for (Object entry : sort(attributes).entrySet()) { sb.append(((Map.Entry) entry).getKey()); sb.append(DELIMITER); appendObject(sb, ((Map.Entry) entry).getValue()); sb.append(DELIMITER); } } private static void appendObject(StringBuilder sb, Object value) { if (value instanceof Object[] arrayValue) { sb.append(Arrays.toString(arrayValue)); } else if (value instanceof Map<?, ?> map) { appendMap(sb, map); } else if (value instanceof IndexType indexType) { sb.append(indexType.format()); } else { sb.append(value); } } private static SortedMap<?, ?> sort(Map<?, ?> map) { if (map instanceof ImmutableSortedMap) { return (ImmutableSortedMap<?, ?>) map; } return ImmutableSortedMap.copyOf(map); } }
3,029
33.827586
125
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/IndexType.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import com.google.common.base.Splitter; import java.util.List; import java.util.Objects; import javax.annotation.concurrent.Immutable; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; public abstract class IndexType { public static final String FIELD_INDEX_TYPE = "indexType"; private static final String SEPARATOR = "/"; private static final Splitter SEPARATOR_SPLITTER = Splitter.on(SEPARATOR); public abstract IndexMainType getMainType(); public abstract String format(); /** * Parse a String generated by {@link #format()} to extract the simple details of the main type. * <p> * Note: neither {@link IndexMainType} nor {@link IndexRelationType} can be parsed from the string generated by * {@link #format()} as the generated string does not contain the {@link Index#acceptsRelations() acceptsRelations} * flag). */ public static SimpleIndexMainType parseMainType(String s) { List<String> split = SEPARATOR_SPLITTER.splitToList(s); checkArgument(split.size() >= 2, "Unsupported IndexType value: %s", s); return new SimpleIndexMainType(split.get(0), split.get(1)); } @Immutable public static final class SimpleIndexMainType { private final String index; private final String type; private SimpleIndexMainType(String index, String type) { this.index = index; this.type = type; } public String getIndex() { return index; } public String getType() { return type; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SimpleIndexMainType that = (SimpleIndexMainType) o; return index.equals(that.index) && type.equals(that.type); } @Override public int hashCode() { return Objects.hash(index, type); } @Override public String toString() { return "[" + index + '/' + type + ']'; } } public static IndexMainType main(Index index, String type) { return new IndexMainType(index, type); } public static IndexRelationType relation(IndexMainType mainType, String name) { checkArgument(mainType.getIndex().acceptsRelations(), "Index must define a join field to have relations"); return new IndexRelationType(mainType, name); } @Immutable public static final class IndexMainType extends IndexType { private final Index index; private final String type; private final String key; private IndexMainType(Index index, String type) { this.index = requireNonNull(index); checkArgument(type != null && !type.isEmpty(), "type name can't be null nor empty"); this.type = type; this.key = index.getName() + SEPARATOR + type; } @Override public IndexMainType getMainType() { return this; } public Index getIndex() { return index; } public String getType() { return type; } @Override public String format() { return key; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IndexMainType indexType = (IndexMainType) o; return index.equals(indexType.index) && type.equals(indexType.type); } @Override public int hashCode() { return Objects.hash(index, type); } @Override public String toString() { return "[" + key + "]"; } } @Immutable public static final class IndexRelationType extends IndexType { private final IndexMainType mainType; private final String name; private IndexRelationType(IndexMainType mainType, String name) { this.mainType = mainType; checkArgument(name != null && !name.isEmpty(), "type name can't be null nor empty"); this.name = name; } @Override public IndexMainType getMainType() { return mainType; } public String getName() { return name; } @Override public String format() { return mainType.index.getName() + "/" + "_doc"; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IndexRelationType indexType = (IndexRelationType) o; return mainType.equals(indexType.mainType) && name.equals(indexType.name); } @Override public int hashCode() { return Objects.hash(mainType, name); } @Override public String toString() { return "[" + mainType.index.getName() + "/" + mainType.type + "/" + name + "]"; } } }
5,678
25.914692
117
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/Indexers.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.util.Collection; import java.util.stream.Collectors; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.entity.EntityDto; public interface Indexers { enum EntityEvent { CREATION, DELETION, PROJECT_KEY_UPDATE, PROJECT_TAGS_UPDATE, PERMISSION_CHANGE } enum BranchEvent { // Note that when a project/app is deleted, no events are sent for each branch removed as part of that process DELETION, MEASURE_CHANGE } /** * Re-index data based on the event. It commits the DB session once any indexation request was written in the same session, * ensuring consistency between the DB and the indexes. Therefore, DB data changes that cause the indexation event should * be done using the same DB session and the session should be uncommitted. */ void commitAndIndexOnEntityEvent(DbSession dbSession, Collection<String> entityUuids, EntityEvent cause); /** * Re-index data based on the event. It commits the DB session once any indexation request was written in the same session, * ensuring consistency between the DB and the indexes. Therefore, DB data changes that cause the indexation event should * be done using the same DB session and the session should be uncommitted. */ void commitAndIndexOnBranchEvent(DbSession dbSession, Collection<String> branchUuids, BranchEvent cause); /** * Re-index data based on the event. It commits the DB session once any indexation request was written in the same session, * ensuring consistency between the DB and the indexes. Therefore, DB data changes that cause the indexation event should * be done using the same DB session and the session should be uncommitted. */ default void commitAndIndexEntities(DbSession dbSession, Collection<? extends EntityDto> entities, EntityEvent cause) { Collection<String> entityUuids = entities.stream() .map(EntityDto::getUuid) .collect(Collectors.toSet()); commitAndIndexOnEntityEvent(dbSession, entityUuids, cause); } /** * Re-index data based on the event. It commits the DB session once any indexation request was written in the same session, * ensuring consistency between the DB and the indexes. Therefore, DB data changes that cause the indexation event should * be done using the same DB session and the session should be uncommitted. */ default void commitAndIndexBranches(DbSession dbSession, Collection<BranchDto> branches, BranchEvent cause) { Collection<String> branchUuids = branches.stream() .map(BranchDto::getUuid) .collect(Collectors.toSet()); commitAndIndexOnBranchEvent(dbSession, branchUuids, cause); } }
3,571
43.098765
125
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/IndexersImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.util.Collection; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import org.sonar.db.DbSession; import org.sonar.db.es.EsQueueDto; import static java.util.Arrays.asList; /** * Delegates events to indexers, that may want to reindex something based on the event. */ public class IndexersImpl implements Indexers { private final List<EventIndexer> indexers; public IndexersImpl(EventIndexer... indexers) { this.indexers = asList(indexers); } /** * Asks all indexers to queue an indexation request in the DB to index the specified entities, if needed (according to * "cause" parameter), then call all indexers to index the requests. * The idea is that the indexation requests are committed into the DB at the same time as the data that caused those requests * to be created, for consistency. * If the indexation fails, the indexation requests will still be in the DB and can be processed again later. */ @Override public void commitAndIndexOnEntityEvent(DbSession dbSession, Collection<String> entityUuids, EntityEvent cause) { indexOnEvent(dbSession, indexer -> indexer.prepareForRecoveryOnEntityEvent(dbSession, entityUuids, cause)); } /** * Asks all indexers to queue an indexation request in the DB to index the specified branches, if needed (according to * "cause" parameter), then call all indexers to index the requests. * The idea is that the indexation requests are committed into the DB at the same time as the data that caused those requests * to be created, for consistency. * If the indexation fails, the indexation requests will still be in the DB and can be processed again later. */ @Override public void commitAndIndexOnBranchEvent(DbSession dbSession, Collection<String> branchUuids, BranchEvent cause) { indexOnEvent(dbSession, indexer -> indexer.prepareForRecoveryOnBranchEvent(dbSession, branchUuids, cause)); } private void indexOnEvent(DbSession dbSession, Function<EventIndexer, Collection<EsQueueDto>> esQueueSupplier) { Map<EventIndexer, Collection<EsQueueDto>> itemsByIndexer = new IdentityHashMap<>(); indexers.forEach(i -> itemsByIndexer.put(i, esQueueSupplier.apply(i))); dbSession.commit(); // ensure that indexer#index() is called only with the item type that it supports itemsByIndexer.forEach((indexer, items) -> indexer.index(dbSession, items)); } }
3,338
42.363636
127
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/IndexingListener.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.util.List; import static java.lang.String.format; public interface IndexingListener { void onSuccess(List<DocId> docIds); void onFinish(IndexingResult result); IndexingListener FAIL_ON_ERROR = new IndexingListener() { @Override public void onSuccess(List<DocId> docIds) { // nothing to do } @Override public void onFinish(IndexingResult result) { if (result.getFailures() > 0) { throw new IllegalStateException( format("Unrecoverable indexation failures: %d errors among %d requests. Check Elasticsearch logs for further details.", result.getFailures(), result.getTotal())); } } }; }
1,567
31
129
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/IndexingResult.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.util.concurrent.atomic.AtomicLong; public class IndexingResult { // FIXME should be private final AtomicLong total = new AtomicLong(0L); private final AtomicLong successes = new AtomicLong(0L); IndexingResult clear() { total.set(0L); successes.set(0L); return this; } public void incrementRequests() { total.incrementAndGet(); } public IndexingResult incrementSuccess() { successes.incrementAndGet(); return this; } public void add(IndexingResult other) { total.addAndGet(other.total.get()); successes.addAndGet(other.successes.get()); } public long getFailures() { return total.get() - successes.get(); } public long getTotal() { return total.get(); } public long getSuccess() { return successes.get(); } public double getSuccessRatio() { return total.get() == 0 ? 1.0 : ((1.0 * successes.get()) / total.get()); } public boolean isSuccess() { return total.get() == successes.get(); } }
1,877
25.828571
76
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/OneToManyResilientIndexingListener.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.util.Collection; import java.util.List; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.es.EsQueueDto; /** * Clean-up the db table "es_queue" when documents * are successfully indexed so that the recovery * daemon does not re-index them. * * This implementation assumes that one row in table es_queue * is associated to multiple index documents. The column * es_queue.doc_id is not equal to ids of documents. * * Important. All the provided EsQueueDto instances must * reference documents involved in the BulkIndexer call, otherwise * some items will be marked as successfully processed, even * if not processed at all. */ public class OneToManyResilientIndexingListener implements IndexingListener { private final DbClient dbClient; private final DbSession dbSession; private final Collection<EsQueueDto> items; public OneToManyResilientIndexingListener(DbClient dbClient, DbSession dbSession, Collection<EsQueueDto> items) { this.dbClient = dbClient; this.dbSession = dbSession; this.items = items; } @Override public void onSuccess(List<DocId> successDocIds) { // it's not possible to deduce which ES_QUEUE row // must be deleted. For example: // items: project P1 // successDocIds: issue 1 and issue 2 // --> no relationship between items and successDocIds } @Override public void onFinish(IndexingResult result) { if (result.isSuccess()) { dbClient.esQueueDao().delete(dbSession, items); dbSession.commit(); } } }
2,429
33.225352
115
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/OneToOneResilientIndexingListener.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import com.google.common.collect.Multimap; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.function.Function; import org.sonar.core.util.stream.MoreCollectors; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.es.EsQueueDto; /** * Clean-up the db table "es_queue" when documents * are successfully indexed so that the recovery * daemon does not re-index them. * * This implementation assumes that one row in table es_queue * is associated to one index document and that es_queue.doc_id * equals document id. */ public class OneToOneResilientIndexingListener implements IndexingListener { private final DbClient dbClient; private final DbSession dbSession; private final Multimap<DocId, EsQueueDto> itemsById; public OneToOneResilientIndexingListener(DbClient dbClient, DbSession dbSession, Collection<EsQueueDto> items) { this.dbClient = dbClient; this.dbSession = dbSession; this.itemsById = items.stream() .collect(MoreCollectors.index(i -> { IndexType.SimpleIndexMainType mainType = IndexType.parseMainType(i.getDocType()); return new DocId(mainType.getIndex(), "_doc", i.getDocId()); }, Function.identity())); } @Override public void onSuccess(List<DocId> successDocIds) { if (!successDocIds.isEmpty()) { Collection<EsQueueDto> itemsToDelete = successDocIds.stream() .map(itemsById::get) .flatMap(Collection::stream) .filter(Objects::nonNull) .toList(); dbClient.esQueueDao().delete(dbSession, itemsToDelete); dbSession.commit(); } } @Override public void onFinish(IndexingResult result) { // nothing to do, items that have been successfully indexed // are already deleted from db (see method onSuccess()) } }
2,706
34.618421
114
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/ResilientIndexer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.util.Collection; import org.sonar.db.DbSession; import org.sonar.db.es.EsQueueDto; /** * Indexers that are resilient. These indexers handle indexation items that are queued in the DB. */ public interface ResilientIndexer extends StartupIndexer { /** * Index the items and delete them from es_queue DB table when the indexation * is done. If there is a failure, the items are kept in DB to be re-processed later. * * @param dbSession the db session * @param items the items to be indexed * @return the number of successful indexed items */ IndexingResult index(DbSession dbSession, Collection<EsQueueDto> items); }
1,532
36.390244
97
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/SearchIdResult.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.time.ZoneId; import java.util.ArrayList; import java.util.List; import java.util.function.Function; import org.apache.commons.lang.builder.ReflectionToStringBuilder; import org.apache.lucene.search.TotalHits; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import static java.util.Optional.ofNullable; public class SearchIdResult<ID> { private final List<ID> uuids; private final Facets facets; private final long total; public SearchIdResult(SearchResponse response, Function<String, ID> converter, ZoneId timeZone) { this.facets = new Facets(response, timeZone); this.total = getTotalHits(response).value; this.uuids = convertToIds(response.getHits(), converter); } private static TotalHits getTotalHits(SearchResponse response) { return ofNullable(response.getHits().getTotalHits()).orElseThrow(() -> new IllegalStateException("Could not get total hits of search results")); } public List<ID> getUuids() { return uuids; } public long getTotal() { return total; } public Facets getFacets() { return this.facets; } @Override public String toString() { return ReflectionToStringBuilder.toString(this); } private static <ID> List<ID> convertToIds(SearchHits hits, Function<String, ID> converter) { List<ID> docs = new ArrayList<>(); for (SearchHit hit : hits.getHits()) { docs.add(converter.apply(hit.getId())); } return docs; } }
2,409
31.133333
148
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/SearchOptions.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.text.JsonWriter; import static com.google.common.base.Preconditions.checkArgument; /** * Various Elasticsearch request options: paging, fields and facets */ public class SearchOptions { public static final int DEFAULT_OFFSET = 0; public static final int DEFAULT_LIMIT = 10; public static final int MAX_PAGE_SIZE = 500; private static final int MAX_RETURNABLE_RESULTS = 10_000; private int offset = DEFAULT_OFFSET; private int limit = DEFAULT_LIMIT; private final Set<String> facets = new LinkedHashSet<>(); private final Set<String> fieldsToReturn = new HashSet<>(); /** * Offset of the first result to return. Defaults to {@link #DEFAULT_OFFSET} */ public int getOffset() { return offset; } /** * Sets the offset of the first result to return (zero-based). */ public SearchOptions setOffset(int offset) { checkArgument(offset >= 0, "Offset must be positive"); this.offset = offset; return this; } /** * Set offset and limit according to page approach */ public SearchOptions setPage(int page, int pageSize) { checkArgument(page >= 1, "Page must be greater or equal to 1 (got " + page + ")"); setLimit(pageSize); int lastResultIndex = page * pageSize; checkArgument(lastResultIndex <= MAX_RETURNABLE_RESULTS, "Can return only the first %s results. %sth result asked.", MAX_RETURNABLE_RESULTS, lastResultIndex); setOffset(lastResultIndex - pageSize); return this; } public int getPage() { return limit > 0 ? (int) Math.ceil((double) (offset + 1) / (double) limit) : 0; } /** * Limit on the number of results to return. Defaults to {@link #DEFAULT_LIMIT}. */ public int getLimit() { return limit; } /** * Sets the limit on the number of results to return. */ public SearchOptions setLimit(int limit) { checkArgument(limit > 0 && limit <= MAX_PAGE_SIZE, "Page size must be between 1 and " + MAX_PAGE_SIZE + " (got " + limit + ")"); this.limit = limit; return this; } /** * Lists selected facets. */ public Collection<String> getFacets() { return facets; } /** * Selects facets to return for the domain. */ public SearchOptions addFacets(@Nullable Collection<String> f) { if (f != null) { this.facets.addAll(f); } return this; } public SearchOptions addFacets(String... array) { Collections.addAll(facets, array); return this; } public Set<String> getFields() { return fieldsToReturn; } public SearchOptions addFields(@Nullable Collection<String> c) { if (c != null) { for (String s : c) { if (StringUtils.isNotBlank(s)) { fieldsToReturn.add(s); } } } return this; } public SearchOptions writeJson(JsonWriter json, long totalHits) { json.prop("total", totalHits); json.prop(WebService.Param.PAGE, getPage()); json.prop(WebService.Param.PAGE_SIZE, getLimit()); return this; } }
4,131
28.304965
162
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/SearchResult.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.time.ZoneId; import java.util.List; import java.util.Map; import java.util.function.Function; import org.apache.commons.lang.builder.ReflectionToStringBuilder; import org.apache.lucene.search.TotalHits; import org.elasticsearch.action.search.SearchResponse; import static java.util.Optional.ofNullable; public class SearchResult<DOC extends BaseDoc> { private final List<DOC> docs; private final Facets facets; private final long total; public SearchResult(SearchResponse response, Function<Map<String, Object>, DOC> converter, ZoneId timeZone) { this.facets = new Facets(response, timeZone); this.total = getTotalHits(response).value; this.docs = EsUtils.convertToDocs(response.getHits(), converter); } private static TotalHits getTotalHits(SearchResponse response) { return ofNullable(response.getHits().getTotalHits()).orElseThrow(() -> new IllegalStateException("Could not get total hits of search results")); } public List<DOC> getDocs() { return docs; } public long getTotal() { return total; } public Facets getFacets() { return this.facets; } @Override public String toString() { return ReflectionToStringBuilder.toString(this); } }
2,099
31.307692
148
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/Sorting.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import java.util.List; import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.SortBuilders; import org.elasticsearch.search.sort.SortOrder; import static com.google.common.base.Preconditions.checkArgument; /** * Construct sorting criteria of ES requests. Sortable fields must be previously * declared with methods prefixed by <code>add</code>. */ public class Sorting { private final ListMultimap<String, Field> fields = ArrayListMultimap.create(); private final List<Field> defaultFields = Lists.newArrayList(); public Field add(String name) { Field field = new Field(name); fields.put(name, field); return field; } public Field add(String name, String fieldName) { Field field = new Field(fieldName); fields.put(name, field); return field; } public Field addDefault(String fieldName) { Field field = new Field(fieldName); defaultFields.add(field); return field; } public List<Field> getFields(String name) { return fields.get(name); } public List<FieldSortBuilder> fill(String name, boolean asc) { List<Field> list = fields.get(name); checkArgument(!list.isEmpty(), "Bad sort field: %s", name); return doFill(list, asc); } public List<FieldSortBuilder> fillDefault() { return doFill(defaultFields, true); } private static List<FieldSortBuilder> doFill(List<Field> fields, boolean asc) { return fields.stream().map(field -> { FieldSortBuilder sortBuilder = SortBuilders.fieldSort(field.name); boolean effectiveAsc = asc != field.reverse; sortBuilder.order(effectiveAsc ? SortOrder.ASC : SortOrder.DESC); boolean effectiveMissingLast = asc == field.missingLast; sortBuilder.missing(effectiveMissingLast ? "_last" : "_first"); return sortBuilder; }).toList(); } public static class Field { private final String name; private boolean reverse = false; private boolean missingLast = false; /** * Default is missing first, same order as requested */ public Field(String name) { this.name = name; } /** * Mark missing value as moved to the end of sorted results if requested sort is ascending. */ public Field missingLast() { missingLast = true; return this; } /** * Mark values as ordered in the opposite direction than the requested sort. */ public Field reverse() { reverse = true; return this; } public String getName() { return name; } public boolean isReverse() { return reverse; } public boolean isMissingLast() { return missingLast; } } }
3,696
28.576
95
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/StartupIndexer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.util.Set; /** * This kind of indexers get initialized during web server startup. */ public interface StartupIndexer { enum Type { SYNCHRONOUS, ASYNCHRONOUS } default Type getType() { return Type.SYNCHRONOUS; } default void triggerAsyncIndexOnStartup(Set<IndexType> uninitializedIndexTypes) { throw new IllegalStateException("ASYNCHRONOUS StartupIndexer must implement initAsyncIndexOnStartup"); } /** * This reindexing method will only be called on startup, and only, * if there is at least one uninitialized type. */ default void indexOnStartup(Set<IndexType> uninitializedIndexTypes) { throw new IllegalStateException("SYNCHRONOUS StartupIndexer must implement indexOnStartup"); } Set<IndexType> getIndexTypes(); }
1,655
31.470588
106
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/StickyFacetBuilder.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es; import java.util.Arrays; import java.util.Map; import java.util.Objects; import java.util.function.Function; import java.util.stream.Collector; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.apache.commons.lang.ArrayUtils; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.search.aggregations.AbstractAggregationBuilder; import org.elasticsearch.search.aggregations.AggregationBuilder; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.BucketOrder; import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.terms.IncludeExclude; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import static java.lang.Math.max; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; public class StickyFacetBuilder { private static final int FACET_DEFAULT_MIN_DOC_COUNT = 1; public static final int FACET_DEFAULT_SIZE = 10; private static final BucketOrder FACET_DEFAULT_ORDER = BucketOrder.count(false); /** In some cases the user selects >15 items for one facet. In that case, we want to calculate the doc count for all of them (not just the first 15 items, which would be the * default for the TermsAggregation). */ private static final int MAXIMUM_NUMBER_OF_SELECTED_ITEMS_WHOSE_DOC_COUNT_WILL_BE_CALCULATED = 50; private static final Collector<CharSequence, ?, String> PIPE_JOINER = Collectors.joining("|"); private final QueryBuilder query; private final Map<String, QueryBuilder> filters; private final AbstractAggregationBuilder subAggregation; private final BucketOrder order; public StickyFacetBuilder(QueryBuilder query, Map<String, QueryBuilder> filters) { this(query, filters, null, FACET_DEFAULT_ORDER); } public StickyFacetBuilder(QueryBuilder query, Map<String, QueryBuilder> filters, @Nullable AbstractAggregationBuilder subAggregation, @Nullable BucketOrder order) { this.query = query; this.filters = filters; this.subAggregation = subAggregation; this.order = order; } public AggregationBuilder buildStickyFacet(String fieldName, String facetName, Object... selected) { return buildStickyFacet(fieldName, facetName, FACET_DEFAULT_SIZE, t -> t, selected); } public AggregationBuilder buildStickyFacet(String fieldName, String facetName, int size, Object... selected) { return buildStickyFacet(fieldName, facetName, size, t -> t, selected); } /** * Creates an aggregation, that will return the top-terms for <code>fieldName</code>. * * It will filter according to the filters of every of the <em>other</em> fields, but will not apply filters to <em>this</em> field (so that the user can see all terms, even * after having chosen for one of the terms). * * If special filtering is required (like for nested types), additional functionality can be passed into the method in the <code>additionalAggregationFilter</code> parameter. * * @param fieldName the name of the field that contains the terms * @param facetName the name of the aggregation (use this for to find the corresponding results in the response) * @param size number of facet items * @param additionalAggregationFilter additional features (like filtering using childQuery) * @param selected the terms, that the user already has selected * @return the (global) aggregation, that can be added on top level of the elasticsearch request */ public AggregationBuilder buildStickyFacet(String fieldName, String facetName, int size, Function<TermsAggregationBuilder, AggregationBuilder> additionalAggregationFilter, Object... selected) { BoolQueryBuilder facetFilter = getStickyFacetFilter(fieldName); FilterAggregationBuilder facetTopAggregation = buildTopFacetAggregation(fieldName, facetName, facetFilter, size, additionalAggregationFilter); facetTopAggregation = addSelectedItemsToFacet(fieldName, facetName, facetTopAggregation, additionalAggregationFilter, selected); return AggregationBuilders .global(facetName) .subAggregation(facetTopAggregation); } public BoolQueryBuilder getStickyFacetFilter(String... fieldNames) { BoolQueryBuilder facetFilter = boolQuery().must(query); for (Map.Entry<String, QueryBuilder> filter : filters.entrySet()) { if (filter.getValue() != null && !ArrayUtils.contains(fieldNames, filter.getKey())) { facetFilter.must(filter.getValue()); } } return facetFilter; } private FilterAggregationBuilder buildTopFacetAggregation(String fieldName, String facetName, BoolQueryBuilder facetFilter, int size, Function<TermsAggregationBuilder, AggregationBuilder> additionalAggregationFilter) { TermsAggregationBuilder termsAggregation = buildTermsFacetAggregation(fieldName, facetName, size); AggregationBuilder improvedAggregation = additionalAggregationFilter.apply(termsAggregation); return AggregationBuilders .filter(facetName + "_filter", facetFilter) .subAggregation(improvedAggregation); } private TermsAggregationBuilder buildTermsFacetAggregation(String fieldName, String facetName, int size) { TermsAggregationBuilder termsAggregation = AggregationBuilders.terms(facetName) .field(fieldName) .order(order) .size(size) .minDocCount(FACET_DEFAULT_MIN_DOC_COUNT); if (subAggregation != null) { termsAggregation = termsAggregation.subAggregation(subAggregation); } return termsAggregation; } public FilterAggregationBuilder addSelectedItemsToFacet(String fieldName, String facetName, FilterAggregationBuilder facetTopAggregation, Function<TermsAggregationBuilder, AggregationBuilder> additionalAggregationFilter, Object... selected) { if (selected.length <= 0) { return facetTopAggregation; } String includes = Arrays.stream(selected) .filter(Objects::nonNull) .map(s -> EsUtils.escapeSpecialRegexChars(s.toString())) .collect(PIPE_JOINER); TermsAggregationBuilder selectedTerms = AggregationBuilders.terms(facetName + "_selected") .size(max(MAXIMUM_NUMBER_OF_SELECTED_ITEMS_WHOSE_DOC_COUNT_WILL_BE_CALCULATED, includes.length())) .field(fieldName) .includeExclude(new IncludeExclude(includes, null)); if (subAggregation != null) { selectedTerms = selectedTerms.subAggregation(subAggregation); } AggregationBuilder improvedAggregation = additionalAggregationFilter.apply(selectedTerms); facetTopAggregation.subAggregation(improvedAggregation); return facetTopAggregation; } }
7,619
47.227848
176
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/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.es; import javax.annotation.ParametersAreNonnullByDefault;
960
37.44
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/metadata/MetadataIndex.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.metadata; import java.util.Optional; import org.sonar.server.es.Index; import org.sonar.server.es.IndexType; public interface MetadataIndex { Optional<String> getHash(Index index); void setHash(Index index, String hash); boolean getInitialized(IndexType indexType); void setInitialized(IndexType indexType, boolean initialized); Optional<String> getDbVendor(); void setDbMetadata(String vendor); }
1,288
32.051282
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/metadata/MetadataIndexDefinition.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.metadata; import org.sonar.api.config.Configuration; import org.sonar.server.es.Index; import org.sonar.server.es.IndexDefinition.IndexDefinitionContext; import org.sonar.server.es.IndexType; import org.sonar.server.es.IndexType.IndexMainType; import org.sonar.server.es.newindex.NewRegularIndex; import static org.sonar.server.es.newindex.SettingsConfiguration.MANUAL_REFRESH_INTERVAL; import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder; public class MetadataIndexDefinition { public static final Index DESCRIPTOR = Index.simple("metadatas"); public static final IndexMainType TYPE_METADATA = IndexType.main(DESCRIPTOR, "metadata"); public static final String FIELD_VALUE = "value"; private static final int DEFAULT_NUMBER_OF_SHARDS = 1; private final Configuration configuration; public MetadataIndexDefinition(Configuration configuration) { this.configuration = configuration; } public void define(IndexDefinitionContext context) { NewRegularIndex index = context.create( DESCRIPTOR, newBuilder(configuration) .setRefreshInterval(MANUAL_REFRESH_INTERVAL) .setDefaultNbOfShards(DEFAULT_NUMBER_OF_SHARDS) .build()); index.createTypeMapping(TYPE_METADATA) .keywordFieldBuilder(FIELD_VALUE).disableSearch().store().build(); } }
2,204
37.017241
91
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/metadata/MetadataIndexImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.metadata; import java.util.Optional; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.common.document.DocumentField; import org.sonar.server.es.EsClient; import org.sonar.server.es.Index; import org.sonar.server.es.IndexType; import org.sonar.server.es.IndexType.IndexMainType; import org.sonar.server.es.IndexType.IndexRelationType; import static org.sonar.server.es.metadata.MetadataIndexDefinition.TYPE_METADATA; import static org.sonar.server.es.newindex.DefaultIndexSettings.REFRESH_IMMEDIATE; public class MetadataIndexImpl implements MetadataIndex { private static final String DB_VENDOR_KEY = "dbVendor"; private final EsClient esClient; public MetadataIndexImpl(EsClient esClient) { this.esClient = esClient; } @Override public Optional<String> getHash(Index index) { return getMetadata(hashId(index)); } @Override public void setHash(Index index, String hash) { setMetadata(hashId(index), hash); } private static String hashId(Index index) { return index.getName() + ".indexStructure"; } @Override public boolean getInitialized(IndexType indexType) { return getMetadata(initializedId(indexType)).map(Boolean::parseBoolean).orElse(false); } @Override public void setInitialized(IndexType indexType, boolean initialized) { setMetadata(initializedId(indexType), String.valueOf(initialized)); } private static String initializedId(IndexType indexType) { if (indexType instanceof IndexMainType mainType) { return mainType.getIndex().getName() + "." + mainType.getType() + ".initialized"; } if (indexType instanceof IndexRelationType relationType) { IndexMainType mainType = relationType.getMainType(); return mainType.getIndex().getName() + "." + mainType.getType() + "." + relationType.getName() + ".initialized"; } throw new IllegalArgumentException("Unsupported IndexType " + indexType.getClass()); } @Override public Optional<String> getDbVendor() { return getMetadata(DB_VENDOR_KEY); } @Override public void setDbMetadata(String vendor) { setMetadata(DB_VENDOR_KEY, vendor); } private Optional<String> getMetadata(String id) { GetResponse response = esClient.get(new GetRequest(TYPE_METADATA.getIndex().getName()) .id(id) .storedFields(MetadataIndexDefinition.FIELD_VALUE)); if (response.isExists()) { DocumentField field = response.getField(MetadataIndexDefinition.FIELD_VALUE); return Optional.of(field.getValue()); } return Optional.empty(); } private void setMetadata(String id, String value) { esClient.index(new IndexRequest(TYPE_METADATA.getIndex().getName()) .id(id) .source(MetadataIndexDefinition.FIELD_VALUE, value) .setRefreshPolicy(REFRESH_IMMEDIATE)); } }
3,786
33.743119
118
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/metadata/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.es.metadata; import javax.annotation.ParametersAreNonnullByDefault;
968
39.375
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/newindex/BuiltIndex.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.newindex; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSortedMap; import java.io.Serializable; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.stream.Collectors; import org.elasticsearch.common.settings.Settings; import org.sonar.server.es.IndexType; import org.sonar.server.es.IndexType.IndexRelationType; import static org.sonar.server.es.IndexType.FIELD_INDEX_TYPE; import static org.sonar.server.es.newindex.DefaultIndexSettings.NORMS; import static org.sonar.server.es.newindex.DefaultIndexSettings.STORE; import static org.sonar.server.es.newindex.DefaultIndexSettings.TYPE; /** * Immutable copy of {@link NewIndex} */ public final class BuiltIndex<T extends NewIndex<T>> { private final IndexType.IndexMainType mainType; private final Set<IndexRelationType> relationTypes; private final Settings settings; private final Map<String, Object> attributes; BuiltIndex(T newIndex) { this.mainType = newIndex.getMainType(); this.settings = newIndex.getSettings().build(); this.relationTypes = newIndex.getRelationsStream().collect(Collectors.toSet()); this.attributes = buildAttributes(newIndex); } private static Map<String, Object> buildAttributes(NewIndex<?> newIndex) { Map<String, Object> indexAttributes = new TreeMap<>(newIndex.getAttributes()); setRouting(indexAttributes, newIndex); indexAttributes.put("properties", buildProperties(newIndex)); return ImmutableSortedMap.copyOf(indexAttributes); } private static void setRouting(Map<String, Object> indexAttributes, NewIndex newIndex) { if (!newIndex.getRelations().isEmpty()) { indexAttributes.put("_routing", ImmutableMap.of("required", true)); } } private static TreeMap<String, Object> buildProperties(NewIndex<?> newIndex) { TreeMap<String, Object> indexProperties = new TreeMap<>(newIndex.getProperties()); setTypeField(indexProperties, newIndex); setJoinField(indexProperties, newIndex); return indexProperties; } private static void setTypeField(TreeMap<String, Object> indexProperties, NewIndex newIndex) { Collection<IndexRelationType> relations = newIndex.getRelations(); if (!relations.isEmpty()) { indexProperties.put( FIELD_INDEX_TYPE, ImmutableMap.of( TYPE, "keyword", NORMS, false, STORE, false, "doc_values", false)); } } private static void setJoinField(TreeMap<String, Object> indexProperties, NewIndex newIndex) { Collection<IndexRelationType> relations = newIndex.getRelations(); IndexType.IndexMainType mainType = newIndex.getMainType(); if (!relations.isEmpty()) { indexProperties.put(mainType.getIndex().getJoinField(), ImmutableMap.of( TYPE, "join", "relations", ImmutableMap.of(mainType.getType(), namesToStringOrStringArray(relations)))); } } private static Serializable namesToStringOrStringArray(Collection<IndexRelationType> relations) { if (relations.size() == 1) { return relations.iterator().next().getName(); } return relations.stream() .map(IndexRelationType::getName) .sorted() .toArray(String[]::new); } public IndexType.IndexMainType getMainType() { return mainType; } public Set<IndexRelationType> getRelationTypes() { return relationTypes; } public Settings getSettings() { return settings; } public Map<String, Object> getAttributes() { return attributes; } }
4,438
34.512
99
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/newindex/DefaultIndexSettings.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.newindex; import java.util.Arrays; import org.elasticsearch.action.support.WriteRequest.RefreshPolicy; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.common.settings.Settings; public class DefaultIndexSettings { /** Minimum length of ngrams. */ public static final int MINIMUM_NGRAM_LENGTH = 2; /** Maximum length of ngrams. */ public static final int MAXIMUM_NGRAM_LENGTH = 15; /** Pattern, that splits the user search input **/ public static final String SEARCH_TERM_TOKENIZER_PATTERN = "[\\s]+"; public static final String ANALYSIS = "index.analysis"; public static final String DELIMITER = "."; public static final String TOKENIZER = "tokenizer"; public static final String FILTER = "filter"; public static final String CHAR_FILTER = "char_filter"; public static final String ANALYZER = "analyzer"; public static final String SEARCH_ANALYZER = "search_analyzer"; public static final String TYPE = "type"; public static final String INDEX = "index"; public static final String INDEX_SEARCHABLE = "true"; public static final String INDEX_NOT_SEARCHABLE = "false"; public static final String FIELD_TYPE_TEXT = "text"; public static final String FIELD_TYPE_KEYWORD = "keyword"; public static final String NORMS = "norms"; public static final String STORE = "store"; public static final String FIELD_FIELDDATA = "fielddata"; public static final String FIELDDATA_ENABLED = "true"; public static final String FIELD_TERM_VECTOR = "term_vector"; public static final String STANDARD = "standard"; public static final String PATTERN = "pattern"; public static final String CUSTOM = "custom"; public static final String KEYWORD = "keyword"; public static final String CLASSIC = "classic"; public static final RefreshPolicy REFRESH_IMMEDIATE = RefreshPolicy.IMMEDIATE; public static final RefreshPolicy REFRESH_NONE = RefreshPolicy.NONE; public static final String TRUNCATE = "truncate"; public static final String SUB_FIELD_DELIMITER = "."; public static final String TRIM = "trim"; public static final String LOWERCASE = "lowercase"; public static final String WHITESPACE = "whitespace"; public static final String STOP = "stop"; public static final String ASCIIFOLDING = "asciifolding"; public static final String PORTER_STEM = "porter_stem"; public static final String MIN_GRAM = "min_gram"; public static final String MAX_GRAM = "max_gram"; public static final String LENGTH = "length"; public static final String HTML_STRIP = "html_strip"; private DefaultIndexSettings() { // only static stuff } public static Settings.Builder defaults() { Settings.Builder builder = Settings.builder() .put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1) .put("index.refresh_interval", "30s"); Arrays.stream(DefaultIndexSettingsElement.values()) .map(DefaultIndexSettingsElement::settings) .forEach(builder::put); return builder; } }
3,863
39.673684
80
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/newindex/DefaultIndexSettingsElement.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.newindex; import com.google.common.collect.ImmutableSortedMap; import java.util.Arrays; import java.util.Locale; import java.util.SortedMap; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings.Builder; import static org.sonar.server.es.newindex.DefaultIndexSettings.ANALYSIS; import static org.sonar.server.es.newindex.DefaultIndexSettings.ANALYZER; import static org.sonar.server.es.newindex.DefaultIndexSettings.ASCIIFOLDING; import static org.sonar.server.es.newindex.DefaultIndexSettings.CHAR_FILTER; import static org.sonar.server.es.newindex.DefaultIndexSettings.DELIMITER; import static org.sonar.server.es.newindex.DefaultIndexSettings.FIELDDATA_ENABLED; import static org.sonar.server.es.newindex.DefaultIndexSettings.FIELD_FIELDDATA; import static org.sonar.server.es.newindex.DefaultIndexSettings.FIELD_TYPE_TEXT; import static org.sonar.server.es.newindex.DefaultIndexSettings.FILTER; import static org.sonar.server.es.newindex.DefaultIndexSettings.HTML_STRIP; import static org.sonar.server.es.newindex.DefaultIndexSettings.INDEX; import static org.sonar.server.es.newindex.DefaultIndexSettings.INDEX_SEARCHABLE; import static org.sonar.server.es.newindex.DefaultIndexSettings.KEYWORD; import static org.sonar.server.es.newindex.DefaultIndexSettings.LOWERCASE; import static org.sonar.server.es.newindex.DefaultIndexSettings.MAXIMUM_NGRAM_LENGTH; import static org.sonar.server.es.newindex.DefaultIndexSettings.MAX_GRAM; import static org.sonar.server.es.newindex.DefaultIndexSettings.MINIMUM_NGRAM_LENGTH; import static org.sonar.server.es.newindex.DefaultIndexSettings.MIN_GRAM; import static org.sonar.server.es.newindex.DefaultIndexSettings.PATTERN; import static org.sonar.server.es.newindex.DefaultIndexSettings.PORTER_STEM; import static org.sonar.server.es.newindex.DefaultIndexSettings.SEARCH_ANALYZER; import static org.sonar.server.es.newindex.DefaultIndexSettings.STANDARD; import static org.sonar.server.es.newindex.DefaultIndexSettings.STOP; import static org.sonar.server.es.newindex.DefaultIndexSettings.SUB_FIELD_DELIMITER; import static org.sonar.server.es.newindex.DefaultIndexSettings.TOKENIZER; import static org.sonar.server.es.newindex.DefaultIndexSettings.TRIM; import static org.sonar.server.es.newindex.DefaultIndexSettings.TYPE; import static org.sonar.server.es.newindex.DefaultIndexSettings.WHITESPACE; public enum DefaultIndexSettingsElement { // Filters WORD_FILTER(FILTER) { @Override protected void setup() { set(TYPE, "word_delimiter"); set("generate_word_parts", true); set("catenate_words", true); set("catenate_numbers", true); set("catenate_all", true); set("split_on_case_change", true); set("preserve_original", true); set("split_on_numerics", true); set("stem_english_possessive", true); } }, NGRAM_FILTER(FILTER) { @Override protected void setup() { set(TYPE, "ngram"); set(MIN_GRAM, MINIMUM_NGRAM_LENGTH); set(MAX_GRAM, MAXIMUM_NGRAM_LENGTH); setList("token_chars", "letter", "digit", "punctuation", "symbol"); } }, // Tokenizers GRAM_TOKENIZER(TOKENIZER) { @Override protected void setup() { set(TYPE, "ngram"); set(MIN_GRAM, MINIMUM_NGRAM_LENGTH); set(MAX_GRAM, MAXIMUM_NGRAM_LENGTH); setList("token_chars", "letter", "digit", "punctuation", "symbol"); } }, PREFIX_TOKENIZER(TOKENIZER) { @Override protected void setup() { set(TYPE, "edge_ngram"); set(MIN_GRAM, MINIMUM_NGRAM_LENGTH); set(MAX_GRAM, MAXIMUM_NGRAM_LENGTH); } }, UUID_MODULE_TOKENIZER(TOKENIZER) { @Override protected void setup() { set(TYPE, PATTERN); set(PATTERN, "\\."); } }, // Analyzers SORTABLE_ANALYZER(ANALYZER) { @Override protected void setup() { set(TOKENIZER, KEYWORD); setList(FILTER, TRIM, LOWERCASE); } @Override public SortedMap<String, String> fieldMapping() { return ImmutableSortedMap.of( TYPE, FIELD_TYPE_TEXT, INDEX, INDEX_SEARCHABLE, ANALYZER, getName(), FIELD_FIELDDATA, FIELDDATA_ENABLED); } }, INDEX_GRAMS_ANALYZER(ANALYZER) { @Override protected void setup() { set(TOKENIZER, GRAM_TOKENIZER); setList(FILTER, TRIM, LOWERCASE); } }, SEARCH_GRAMS_ANALYZER(ANALYZER) { @Override protected void setup() { set(TOKENIZER, WHITESPACE); setList(FILTER, TRIM, LOWERCASE); } @Override public SortedMap<String, String> fieldMapping() { return ImmutableSortedMap.of( TYPE, FIELD_TYPE_TEXT, INDEX, INDEX_SEARCHABLE, ANALYZER, INDEX_GRAMS_ANALYZER.getName(), SEARCH_ANALYZER, getName()); } }, INDEX_PREFIX_ANALYZER(ANALYZER) { @Override protected void setup() { set(TOKENIZER, PREFIX_TOKENIZER); setList(FILTER, TRIM); } }, SEARCH_PREFIX_ANALYZER(ANALYZER) { @Override protected void setup() { set(TOKENIZER, WHITESPACE); setList(FILTER, TRIM); } @Override public SortedMap<String, String> fieldMapping() { return ImmutableSortedMap.of( TYPE, FIELD_TYPE_TEXT, INDEX, INDEX_SEARCHABLE, ANALYZER, INDEX_PREFIX_ANALYZER.getName(), SEARCH_ANALYZER, getName()); } }, INDEX_PREFIX_CASE_INSENSITIVE_ANALYZER(ANALYZER) { @Override protected void setup() { set(TOKENIZER, PREFIX_TOKENIZER); setList(FILTER, TRIM, LOWERCASE); } }, SEARCH_PREFIX_CASE_INSENSITIVE_ANALYZER(ANALYZER) { @Override protected void setup() { set(TOKENIZER, WHITESPACE); setList(FILTER, TRIM, LOWERCASE); } @Override public SortedMap<String, String> fieldMapping() { return ImmutableSortedMap.of( TYPE, FIELD_TYPE_TEXT, INDEX, INDEX_SEARCHABLE, ANALYZER, INDEX_PREFIX_CASE_INSENSITIVE_ANALYZER.getName(), SEARCH_ANALYZER, getName()); } }, USER_INDEX_GRAMS_ANALYZER(ANALYZER) { @Override protected void setup() { set(TOKENIZER, WHITESPACE); setList(FILTER, TRIM, LOWERCASE, NGRAM_FILTER.getName()); } }, USER_SEARCH_GRAMS_ANALYZER(ANALYZER) { @Override protected void setup() { set(TOKENIZER, WHITESPACE); setList(FILTER, TRIM, LOWERCASE); } @Override public SortedMap<String, String> fieldMapping() { return ImmutableSortedMap.of( TYPE, FIELD_TYPE_TEXT, INDEX, INDEX_SEARCHABLE, ANALYZER, USER_INDEX_GRAMS_ANALYZER.getName(), SEARCH_ANALYZER, getName()); } }, INDEX_WORDS_ANALYZER(ANALYZER) { @Override protected void setup() { set(TOKENIZER, STANDARD); setList(FILTER, "word_filter", LOWERCASE, STOP, ASCIIFOLDING, PORTER_STEM); } }, SEARCH_WORDS_ANALYZER(ANALYZER) { @Override protected void setup() { set(TOKENIZER, STANDARD); setList(FILTER, LOWERCASE, STOP, ASCIIFOLDING, PORTER_STEM); } @Override public SortedMap<String, String> fieldMapping() { return ImmutableSortedMap.of( TYPE, FIELD_TYPE_TEXT, INDEX, INDEX_SEARCHABLE, ANALYZER, INDEX_WORDS_ANALYZER.getName(), SEARCH_ANALYZER, getName()); } }, ENGLISH_HTML_ANALYZER(ANALYZER) { @Override protected void setup() { set(TOKENIZER, STANDARD); setList(FILTER, LOWERCASE, STOP, ASCIIFOLDING, PORTER_STEM); setList(CHAR_FILTER, HTML_STRIP); } @Override public SortedMap<String, String> fieldMapping() { return ImmutableSortedMap.of( TYPE, FIELD_TYPE_TEXT, INDEX, INDEX_SEARCHABLE, ANALYZER, getName()); } }, PATH_ANALYZER(ANALYZER) { @Override protected void setup() { set(TOKENIZER, "path_hierarchy"); } }, UUID_MODULE_ANALYZER(ANALYZER) { @Override protected void setup() { set(TOKENIZER, UUID_MODULE_TOKENIZER); setList(FILTER, TRIM); } }, ; private final String type; private final String name; private Builder builder = Settings.builder(); DefaultIndexSettingsElement(String type) { this.type = type; this.name = name().toLowerCase(Locale.ENGLISH); setup(); } protected void set(String settingSuffix, int value) { put(localName(settingSuffix), Integer.toString(value)); } protected void set(String settingSuffix, boolean value) { put(localName(settingSuffix), Boolean.toString(value)); } protected void set(String settingSuffix, DefaultIndexSettingsElement otherElement) { put(localName(settingSuffix), otherElement.name); } protected void set(String settingSuffix, String value) { put(localName(settingSuffix), value); } protected void setList(String settingSuffix, String... values) { putList(localName(settingSuffix), values); } protected void setList(String settingSuffix, DefaultIndexSettingsElement... values) { putList(localName(settingSuffix), Arrays.stream(values).map(DefaultIndexSettingsElement::getName).toArray(String[]::new)); } private void put(String setting, String value) { builder = builder.put(setting, value); } private void putList(String setting, String... values) { builder = builder.putList(setting, values); } private String localName(String settingSuffix) { return ANALYSIS + DELIMITER + type + DELIMITER + name + DELIMITER + settingSuffix; } public Settings settings() { return builder.build(); } protected abstract void setup(); public SortedMap<String, String> fieldMapping() { throw new UnsupportedOperationException("The elasticsearch configuration element '" + name + "' cannot be used as field mapping."); } public String subField(String fieldName) { return fieldName + SUB_FIELD_DELIMITER + getSubFieldSuffix(); } public String getSubFieldSuffix() { return getName(); } public String getName() { return name; } }
10,872
28.70765
135
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/newindex/FieldAware.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.newindex; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSortedMap; import java.util.Map; import java.util.TreeMap; import static com.google.common.base.Preconditions.checkArgument; import static org.sonar.server.es.IndexType.FIELD_INDEX_TYPE; import static org.sonar.server.es.newindex.DefaultIndexSettings.ANALYZER; import static org.sonar.server.es.newindex.DefaultIndexSettings.FIELD_TYPE_TEXT; import static org.sonar.server.es.newindex.DefaultIndexSettings.INDEX; import static org.sonar.server.es.newindex.DefaultIndexSettings.TYPE; import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.UUID_MODULE_ANALYZER; public abstract class FieldAware<U extends FieldAware<U>> { abstract U setFieldImpl(String fieldName, Object attributes); protected final U setField(String fieldName, Object attributes) { checkArgument(!FIELD_INDEX_TYPE.equalsIgnoreCase(fieldName), "%s is a reserved field name", FIELD_INDEX_TYPE); return setFieldImpl(fieldName, attributes); } @SuppressWarnings("unchecked") public KeywordFieldBuilder<U> keywordFieldBuilder(String fieldName) { return new KeywordFieldBuilder(this, fieldName); } @SuppressWarnings("unchecked") public TextFieldBuilder<U> textFieldBuilder(String fieldName) { return new TextFieldBuilder(this, fieldName); } @SuppressWarnings("unchecked") public NestedFieldBuilder<U> nestedFieldBuilder(String fieldName) { return new NestedFieldBuilder(this, fieldName); } public U createBooleanField(String fieldName) { return setField(fieldName, ImmutableMap.of("type", "boolean")); } public U createByteField(String fieldName) { return setField(fieldName, ImmutableMap.of("type", "byte")); } public U createDateTimeField(String fieldName) { Map<String, String> hash = new TreeMap<>(); hash.put("type", "date"); hash.put("format", "date_time||epoch_millis"); return setField(fieldName, hash); } public U createDoubleField(String fieldName) { return setField(fieldName, ImmutableMap.of("type", "double")); } public U createIntegerField(String fieldName) { return setField(fieldName, ImmutableMap.of("type", "integer")); } public U createLongField(String fieldName) { return setField(fieldName, ImmutableMap.of("type", "long")); } public U createShortField(String fieldName) { return setField(fieldName, ImmutableMap.of("type", "short")); } public U createUuidPathField(String fieldName) { return setField(fieldName, ImmutableSortedMap.of( TYPE, FIELD_TYPE_TEXT, INDEX, DefaultIndexSettings.INDEX_SEARCHABLE, ANALYZER, UUID_MODULE_ANALYZER.getName())); } }
3,574
35.479592
114
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/newindex/KeywordFieldBuilder.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.newindex; import static org.sonar.server.es.newindex.DefaultIndexSettings.FIELD_TYPE_KEYWORD; public class KeywordFieldBuilder<U extends FieldAware<U>> extends StringFieldBuilder<U, KeywordFieldBuilder<U>> { protected KeywordFieldBuilder(U indexType, String fieldName) { super(indexType, fieldName); } @Override protected boolean getFieldData() { return false; } protected String getFieldType() { return FIELD_TYPE_KEYWORD; } /** * By default, field is stored on disk in a column-stride fashion, so that it can later be used for sorting, * aggregations, or scripting. * Disabling this reduces the size of the index and drop the constraint of single term max size of * 32766 bytes (which, if there is no tokenizing enabled on the field, equals the size of the whole data). */ public KeywordFieldBuilder disableSortingAndAggregating() { this.disabledDocValues = true; return this; } }
1,815
35.32
113
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/newindex/NestedFieldBuilder.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.newindex; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSortedMap; import java.util.Map; import java.util.TreeMap; import static com.google.common.base.Preconditions.checkArgument; import static org.sonar.server.es.newindex.DefaultIndexSettings.FIELD_TYPE_KEYWORD; import static org.sonar.server.es.newindex.DefaultIndexSettings.INDEX; import static org.sonar.server.es.newindex.DefaultIndexSettings.INDEX_SEARCHABLE; public class NestedFieldBuilder<U extends FieldAware<U>> { private final U parent; private final String fieldName; private final Map<String, Object> properties = new TreeMap<>(); protected NestedFieldBuilder(U parent, String fieldName) { this.parent = parent; this.fieldName = fieldName; } private NestedFieldBuilder setProperty(String fieldName, Object value) { properties.put(fieldName, value); return this; } public NestedFieldBuilder addKeywordField(String fieldName) { return setProperty(fieldName, ImmutableSortedMap.of( "type", FIELD_TYPE_KEYWORD, INDEX, INDEX_SEARCHABLE)); } public NestedFieldBuilder addDoubleField(String fieldName) { return setProperty(fieldName, ImmutableMap.of("type", "double")); } public NestedFieldBuilder addIntegerField(String fieldName) { return setProperty(fieldName, ImmutableMap.of("type", "integer")); } public U build() { checkArgument(!properties.isEmpty(), "At least one sub-field must be declared in nested property '%s'", fieldName); return parent.setField(fieldName, ImmutableSortedMap.of( "type", "nested", "properties", properties)); } }
2,519
35
119
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/newindex/NewAuthorizedIndex.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.newindex; import org.sonar.server.es.Index; import org.sonar.server.es.IndexType; import org.sonar.server.es.IndexType.IndexRelationType; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; 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; import static org.sonar.server.permission.index.IndexAuthorizationConstants.TYPE_AUTHORIZATION; public class NewAuthorizedIndex extends NewIndex<NewAuthorizedIndex> { private final IndexType.IndexMainType mainType; public NewAuthorizedIndex(Index index, SettingsConfiguration settingsConfiguration) { super(index, settingsConfiguration); checkArgument(index.acceptsRelations(), "Index must accept relations"); this.mainType = IndexType.main(index, TYPE_AUTHORIZATION); super.createTypeMapping(mainType) .keywordFieldBuilder(FIELD_GROUP_IDS).build() .keywordFieldBuilder(FIELD_USER_IDS).build() .createBooleanField(FIELD_ALLOW_ANYONE); } @Override public IndexType.IndexMainType getMainType() { return mainType; } @Override public TypeMapping createTypeMapping(IndexRelationType relationType) { checkArgument(relationType.getMainType().equals(mainType), "mainType of relation must be %s", mainType); return super.createTypeMapping(relationType); } @Override public BuiltIndex<NewAuthorizedIndex> build() { checkState(!getRelations().isEmpty(), "At least one relation mapping must be defined"); return new BuiltIndex<>(this); } }
2,634
39.538462
108
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/newindex/NewIndex.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.newindex; import com.google.common.collect.ImmutableSortedMap; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; import java.util.stream.Stream; import javax.annotation.CheckForNull; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.common.settings.Settings; import org.sonar.api.config.Configuration; import org.sonar.server.es.Index; import org.sonar.server.es.IndexType.IndexMainType; import org.sonar.server.es.IndexType.IndexRelationType; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static java.lang.String.valueOf; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.process.ProcessProperties.Property.SEARCH_REPLICAS; public abstract class NewIndex<T extends NewIndex<T>> { private static final String ENABLED = "enabled"; private final Index index; private final Map<String, IndexRelationType> relations = new LinkedHashMap<>(); private final Settings.Builder settings = DefaultIndexSettings.defaults(); private final Map<String, Object> attributes = new TreeMap<>(); private final Map<String, Object> properties = new TreeMap<>(); public NewIndex(Index index, SettingsConfiguration settingsConfiguration) { this.index = index; applySettingsConfiguration(settingsConfiguration); configureDefaultAttributes(); } private void applySettingsConfiguration(SettingsConfiguration settingsConfiguration) { settings.put("index.refresh_interval", refreshInterval(settingsConfiguration)); Configuration config = settingsConfiguration.getConfiguration(); boolean clusterMode = config.getBoolean(CLUSTER_ENABLED.getKey()).orElse(false); int shards = config.getInt(String.format("sonar.search.%s.shards", index.getName())) .orElse(settingsConfiguration.getDefaultNbOfShards()); int replicas = clusterMode ? config.getInt(SEARCH_REPLICAS.getKey()).orElse(1) : 0; settings.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, shards); settings.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, replicas); settings.put("index.max_ngram_diff", DefaultIndexSettings.MAXIMUM_NGRAM_LENGTH - DefaultIndexSettings.MINIMUM_NGRAM_LENGTH); } private void configureDefaultAttributes() { attributes.put("dynamic", valueOf(false)); attributes.put("_source", ImmutableSortedMap.of(ENABLED, true)); } private static String refreshInterval(SettingsConfiguration settingsConfiguration) { int refreshInterval = settingsConfiguration.getRefreshInterval(); if (refreshInterval == -1) { return "-1"; } return refreshInterval + "s"; } protected Index getIndex() { return index; } public abstract IndexMainType getMainType(); Collection<IndexRelationType> getRelations() { return relations.values(); } /** * Public, read-only version of {@link #getRelations()} */ public Stream<IndexRelationType> getRelationsStream() { return relations.values().stream(); } Settings.Builder getSettings() { return settings; } @CheckForNull public String getSetting(String key) { return settings.get(key); } protected TypeMapping createTypeMapping(IndexMainType mainType) { checkArgument(mainType.getIndex().equals(index), "Main type must belong to index %s", index); return new TypeMapping(this); } protected TypeMapping createTypeMapping(IndexRelationType relationType) { checkAcceptsRelations(); IndexMainType mainType = getMainType(); checkArgument(relationType.getMainType().equals(mainType), "mainType of relation must be %s", mainType); String relationName = relationType.getName(); checkArgument(!relations.containsKey(relationName), "relation %s already exists", relationName); relations.put(relationName, relationType); return new TypeMapping(this); } private void checkAcceptsRelations() { checkState(getMainType().getIndex().acceptsRelations(), "Index is not configured to accept relations. Update IndexDefinition.Descriptor instance for this index"); } /** * Complete the json hash named "properties" in mapping type, usually to declare fields */ void setFieldImpl(String fieldName, Object attributes) { properties.put(fieldName, attributes); } public T setEnableSource(boolean enableSource) { attributes.put("_source", ImmutableSortedMap.of(ENABLED, enableSource)); return castThis(); } @SuppressWarnings("unchecked") private T castThis() { return (T) this; } public Map<String, Object> getAttributes() { return attributes; } Map<String, Object> getProperties() { return properties; } @CheckForNull public Object getProperty(String key) { return properties.get(key); } public abstract BuiltIndex<T> build(); }
5,770
34.623457
166
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/newindex/NewRegularIndex.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.newindex; import org.sonar.server.es.Index; import org.sonar.server.es.IndexType; import org.sonar.server.es.IndexType.IndexMainType; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; public class NewRegularIndex extends NewIndex<NewRegularIndex> { private IndexMainType mainType; public NewRegularIndex(Index index, SettingsConfiguration settingsConfiguration) { super(index, settingsConfiguration); } @Override public IndexMainType getMainType() { checkState(mainType != null, "Main type has not been defined"); return mainType; } @Override public TypeMapping createTypeMapping(IndexMainType mainType) { checkState(this.mainType == null, "Main type can only be defined once"); this.mainType = mainType; return super.createTypeMapping(mainType); } @Override public TypeMapping createTypeMapping(IndexType.IndexRelationType relationType) { checkState(mainType != null, "Mapping for main type must be created first"); checkArgument(relationType.getMainType().equals(mainType), "main type of relation must be %s", mainType); return super.createTypeMapping(relationType); } @Override public BuiltIndex<NewRegularIndex> build() { checkState(mainType != null, "Mapping for main type must be defined"); checkState(!mainType.getIndex().acceptsRelations() || !getRelations().isEmpty(), "At least one relation must be defined when index accepts relations"); return new BuiltIndex<>(this); } }
2,420
37.428571
155
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/newindex/SettingsConfiguration.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.newindex; import org.sonar.api.config.Configuration; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; public class SettingsConfiguration { public static final int MANUAL_REFRESH_INTERVAL = -1; private final Configuration configuration; private final int defaultNbOfShards; private final int refreshInterval; private SettingsConfiguration(Builder builder) { this.configuration = builder.configuration; this.defaultNbOfShards = builder.defaultNbOfShards; this.refreshInterval = builder.refreshInterval; } public static Builder newBuilder(Configuration configuration) { return new Builder(configuration); } public Configuration getConfiguration() { return configuration; } public int getDefaultNbOfShards() { return defaultNbOfShards; } public int getRefreshInterval() { return refreshInterval; } public static class Builder { private final Configuration configuration; private int defaultNbOfShards = 1; private int refreshInterval = 30; public Builder(Configuration configuration) { this.configuration = requireNonNull(configuration, "configuration can't be null"); } public Builder setDefaultNbOfShards(int defaultNbOfShards) { checkArgument(defaultNbOfShards >= 1, "defaultNbOfShards must be >= 1"); this.defaultNbOfShards = defaultNbOfShards; return this; } public Builder setRefreshInterval(int refreshInterval) { checkArgument(refreshInterval == -1 || refreshInterval > 0, "refreshInterval must be either -1 or strictly positive"); this.refreshInterval = refreshInterval; return this; } public SettingsConfiguration build() { return new SettingsConfiguration(this); } } }
2,687
31
88
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/newindex/StringFieldBuilder.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.newindex; import com.google.common.collect.Maps; import java.util.Arrays; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import static java.lang.String.valueOf; import static org.sonar.server.es.newindex.DefaultIndexSettings.FIELDDATA_ENABLED; import static org.sonar.server.es.newindex.DefaultIndexSettings.FIELD_FIELDDATA; import static org.sonar.server.es.newindex.DefaultIndexSettings.FIELD_TERM_VECTOR; import static org.sonar.server.es.newindex.DefaultIndexSettings.FIELD_TYPE_KEYWORD; import static org.sonar.server.es.newindex.DefaultIndexSettings.INDEX; import static org.sonar.server.es.newindex.DefaultIndexSettings.INDEX_NOT_SEARCHABLE; import static org.sonar.server.es.newindex.DefaultIndexSettings.INDEX_SEARCHABLE; import static org.sonar.server.es.newindex.DefaultIndexSettings.NORMS; import static org.sonar.server.es.newindex.DefaultIndexSettings.STORE; /** * Helper to define a string field in mapping of index type */ public abstract class StringFieldBuilder<U extends FieldAware<U>, T extends StringFieldBuilder<U, T>> { private final U parent; private final String fieldName; private boolean disableSearch = false; private boolean disableNorms = false; private boolean termVectorWithPositionOffsets = false; private SortedMap<String, Object> subFields = Maps.newTreeMap(); private boolean store = false; protected boolean disabledDocValues = false; protected StringFieldBuilder(U parent, String fieldName) { this.parent = parent; this.fieldName = fieldName; } /** * Add a sub-field. A {@code SortedMap} is required for consistency of the index settings hash. */ private T addSubField(String fieldName, SortedMap<String, String> fieldDefinition) { subFields.put(fieldName, fieldDefinition); return castThis(); } /** * Add subfields, one for each analyzer. */ public T addSubFields(DefaultIndexSettingsElement... analyzers) { Arrays.stream(analyzers) .forEach(analyzer -> addSubField(analyzer.getSubFieldSuffix(), analyzer.fieldMapping())); return castThis(); } /** * Norms consume useless memory if string field is used solely for filtering or aggregations. * * https://www.elastic.co/guide/en/elasticsearch/reference/2.3/norms.html * https://www.elastic.co/guide/en/elasticsearch/guide/current/scoring-theory.html#field-norm */ public T disableNorms() { this.disableNorms = true; return castThis(); } /** * Position offset term vectors are required for the fast_vector_highlighter (fvh). */ public T termVectorWithPositionOffsets() { this.termVectorWithPositionOffsets = true; return castThis(); } /** * "index: false" -> Make this field not searchable. * By default field is "true": it is searchable, but index the value exactly * as specified. */ public T disableSearch() { this.disableSearch = true; return castThis(); } public T store() { this.store = true; return castThis(); } @SuppressWarnings("unchecked") private T castThis() { return (T) this; } public U build() { if (subFields.isEmpty()) { return buildWithoutSubfields(); } return buildWithSubfields(); } private U buildWithoutSubfields() { Map<String, Object> hash = new TreeMap<>(); hash.put("type", getFieldType()); hash.put(INDEX, disableSearch ? INDEX_NOT_SEARCHABLE : INDEX_SEARCHABLE); hash.put(NORMS, valueOf(!disableNorms)); hash.put(STORE, valueOf(store)); if (FIELD_TYPE_KEYWORD.equals(getFieldType())) { hash.put("doc_values", valueOf(!disabledDocValues)); } if (getFieldData()) { hash.put(FIELD_FIELDDATA, FIELDDATA_ENABLED); } return parent.setField(fieldName, hash); } private U buildWithSubfields() { Map<String, Object> hash = new TreeMap<>(); hash.put("type", getFieldType()); hash.put(INDEX, disableSearch ? INDEX_NOT_SEARCHABLE : INDEX_SEARCHABLE); hash.put(NORMS, "false"); hash.put(STORE, valueOf(store)); if (FIELD_TYPE_KEYWORD.equals(getFieldType())) { hash.put("doc_values", valueOf(!disabledDocValues)); } if (getFieldData()) { hash.put(FIELD_FIELDDATA, FIELDDATA_ENABLED); } if (termVectorWithPositionOffsets) { hash.put(FIELD_TERM_VECTOR, "with_positions_offsets"); } hash.put("fields", configureSubFields()); return parent.setField(fieldName, hash); } private Map<String, Object> configureSubFields() { Map<String, Object> multiFields = new TreeMap<>(subFields); // apply this fields configuration to all subfields multiFields.entrySet().forEach(entry -> { Object subFieldMapping = entry.getValue(); if (subFieldMapping instanceof Map) { entry.setValue(configureSubField((Map<String, String>) subFieldMapping)); } }); return multiFields; } private Map<String, String> configureSubField(Map<String, String> subFieldMapping) { Map<String, String> subHash = new TreeMap<>(subFieldMapping); subHash.put(INDEX, INDEX_SEARCHABLE); subHash.put(NORMS, "false"); subHash.put(STORE, valueOf(store)); if (termVectorWithPositionOffsets) { subHash.put(FIELD_TERM_VECTOR, "with_positions_offsets"); } return subHash; } protected abstract boolean getFieldData(); protected abstract String getFieldType(); }
6,242
33.302198
103
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/newindex/TextFieldBuilder.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.newindex; import static org.sonar.server.es.newindex.DefaultIndexSettings.FIELD_TYPE_TEXT; public class TextFieldBuilder<U extends FieldAware<U>> extends StringFieldBuilder<U, TextFieldBuilder<U>> { private boolean fieldData = false; protected TextFieldBuilder(U indexType, String fieldName) { super(indexType, fieldName); } protected String getFieldType() { return FIELD_TYPE_TEXT; } /** * Required to enable sorting, aggregation and access to field data on fields of type "text". * <p>Disabled by default as this can have significant memory cost</p> */ public StringFieldBuilder withFieldData() { this.fieldData = true; return this; } @Override protected boolean getFieldData() { return fieldData; } }
1,633
31.68
107
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/newindex/TypeMapping.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.newindex; public class TypeMapping extends FieldAware<TypeMapping> { private final NewIndex<?> newIndex; TypeMapping(NewIndex<?> newIndex) { this.newIndex = newIndex; } @Override TypeMapping setFieldImpl(String fieldName, Object attributes) { newIndex.setFieldImpl(fieldName, attributes); return this; } }
1,206
31.621622
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/newindex/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.es.newindex; import javax.annotation.ParametersAreNonnullByDefault;
969
37.8
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/response/ClusterStatsResponse.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.response; import com.google.gson.JsonObject; import javax.annotation.concurrent.Immutable; import org.elasticsearch.cluster.health.ClusterHealthStatus; @Immutable public class ClusterStatsResponse { private final ClusterHealthStatus healthStatus; private final int nodeCount; private ClusterStatsResponse(JsonObject clusterStatsJson) { this.healthStatus = ClusterHealthStatus.fromString(clusterStatsJson.get("status").getAsString()); this.nodeCount = clusterStatsJson.getAsJsonObject("nodes").getAsJsonObject("count").get("total").getAsInt(); } public static ClusterStatsResponse toClusterStatsResponse(JsonObject jsonObject) { return new ClusterStatsResponse(jsonObject); } public ClusterHealthStatus getHealthStatus() { return healthStatus; } public int getNodeCount() { return nodeCount; } }
1,713
33.979592
112
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/response/IndexStats.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.response; import com.google.gson.JsonObject; import javax.annotation.concurrent.Immutable; @Immutable public class IndexStats { private final String name; private final long docCount; private final long shardsCount; private final long storeSizeBytes; private IndexStats(String name, JsonObject indexStatsJson) { this.name = name; this.docCount = indexStatsJson.getAsJsonObject().getAsJsonObject("primaries").getAsJsonObject("docs").get("count").getAsLong(); this.shardsCount = indexStatsJson.getAsJsonObject().getAsJsonObject("shards").size(); this.storeSizeBytes = indexStatsJson.getAsJsonObject().getAsJsonObject("primaries").getAsJsonObject("store").get("size_in_bytes").getAsLong(); } static IndexStats toIndexStats(String name, JsonObject indexStatsJson) { return new IndexStats(name, indexStatsJson); } public String getName() { return name; } public long getDocCount() { return docCount; } public long getShardsCount() { return shardsCount; } public long getStoreSizeBytes() { return storeSizeBytes; } }
1,958
32.20339
146
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/response/IndicesStats.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.response; import com.google.gson.JsonObject; import javax.annotation.concurrent.Immutable; @Immutable public class IndicesStats { private static final String MEMORY_SIZE_IN_BYTES_ATTRIBUTE_NAME = "memory_size_in_bytes"; private final long storeSizeInBytes; private final long translogSizeInBytes; private final long requestCacheMemorySizeInBytes; private final long fieldDataMemorySizeInBytes; private final long queryCacheMemorySizeInBytes; private IndicesStats(JsonObject indicesStatsJson) { this.storeSizeInBytes = indicesStatsJson.getAsJsonObject("store").get("size_in_bytes").getAsLong(); this.translogSizeInBytes = indicesStatsJson.getAsJsonObject("translog").get("size_in_bytes").getAsLong(); this.requestCacheMemorySizeInBytes = indicesStatsJson.getAsJsonObject("request_cache").get(MEMORY_SIZE_IN_BYTES_ATTRIBUTE_NAME).getAsLong(); this.fieldDataMemorySizeInBytes = indicesStatsJson.getAsJsonObject("fielddata").get(MEMORY_SIZE_IN_BYTES_ATTRIBUTE_NAME).getAsLong(); this.queryCacheMemorySizeInBytes = indicesStatsJson.getAsJsonObject("query_cache").get(MEMORY_SIZE_IN_BYTES_ATTRIBUTE_NAME).getAsLong(); } public static IndicesStats toIndicesStats(JsonObject jsonObject) { return new IndicesStats(jsonObject); } public long getStoreSizeInBytes() { return storeSizeInBytes; } public long getTranslogSizeInBytes() { return translogSizeInBytes; } public long getRequestCacheMemorySizeInBytes() { return requestCacheMemorySizeInBytes; } public long getFieldDataMemorySizeInBytes() { return fieldDataMemorySizeInBytes; } public long getQueryCacheMemorySizeInBytes() { return queryCacheMemorySizeInBytes; } }
2,575
38.030303
144
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/response/IndicesStatsResponse.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.response; import com.google.common.collect.ImmutableMap; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.util.Collection; import java.util.Map; import javax.annotation.concurrent.Immutable; @Immutable public class IndicesStatsResponse { private final ImmutableMap<String, IndexStats> indexStatsMap; private IndicesStatsResponse(JsonObject indicesStats) { ImmutableMap.Builder<String, IndexStats> builder = ImmutableMap.builder(); for (Map.Entry<String, JsonElement> indexStats : indicesStats.getAsJsonObject("indices").entrySet()) { builder.put(indexStats.getKey(), IndexStats.toIndexStats(indexStats.getKey(), indexStats.getValue().getAsJsonObject())); } this.indexStatsMap = builder.build(); } public static IndicesStatsResponse toIndicesStatsResponse(JsonObject jsonObject) { return new IndicesStatsResponse(jsonObject); } public Collection<IndexStats> getAllIndexStats() { return indexStatsMap.values(); } }
1,869
35.666667
126
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/response/JvmStats.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.response; import com.google.gson.JsonObject; import javax.annotation.concurrent.Immutable; @Immutable public class JvmStats { private final long heapUsedPercent; private final long heapUsedInBytes; private final long heapMaxInBytes; private final long nonHeapUsedInBytes; private final long threadCount; private JvmStats(JsonObject jvmStatsJson) { this.heapUsedPercent = jvmStatsJson.getAsJsonObject("mem").get("heap_used_percent").getAsLong(); this.heapUsedInBytes = jvmStatsJson.getAsJsonObject("mem").get("heap_used_in_bytes").getAsLong(); this.heapMaxInBytes = jvmStatsJson.getAsJsonObject("mem").get("heap_max_in_bytes").getAsLong(); this.nonHeapUsedInBytes = jvmStatsJson.getAsJsonObject("mem").get("non_heap_used_in_bytes").getAsLong(); this.threadCount = jvmStatsJson.getAsJsonObject("threads").get("count").getAsLong(); } public static JvmStats toJvmStats(JsonObject jvmStatsJson) { return new JvmStats(jvmStatsJson); } public long getHeapUsedPercent() { return heapUsedPercent; } public long getHeapUsedInBytes() { return heapUsedInBytes; } public long getHeapMaxInBytes() { return heapMaxInBytes; } public long getNonHeapUsedInBytes() { return nonHeapUsedInBytes; } public long getThreadCount() { return threadCount; } }
2,194
32.769231
108
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/response/NodeStats.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.response; import com.google.gson.JsonObject; import javax.annotation.concurrent.Immutable; @Immutable public class NodeStats { private static final String PROCESS_ATTRIBUTE_NAME = "process"; private static final String BREAKERS_ATTRIBUTE_NAME = "breakers"; private final String name; private final String host; private final long cpuUsage; private final long openFileDescriptors; private final long maxFileDescriptors; private final long diskAvailableBytes; private final long diskTotalBytes; private final long fieldDataCircuitBreakerLimit; private final long fieldDataCircuitBreakerEstimation; private final long requestCircuitBreakerLimit; private final long requestCircuitBreakerEstimation; private final JvmStats jvmStats; private final IndicesStats indicesStats; private NodeStats(JsonObject nodeStatsJson) { this.name = nodeStatsJson.get("name").getAsString(); this.host = nodeStatsJson.get("host").getAsString(); this.cpuUsage = nodeStatsJson.getAsJsonObject(PROCESS_ATTRIBUTE_NAME).getAsJsonObject("cpu").get("percent").getAsLong(); this.openFileDescriptors = nodeStatsJson.getAsJsonObject(PROCESS_ATTRIBUTE_NAME).get("open_file_descriptors").getAsLong(); this.maxFileDescriptors = nodeStatsJson.getAsJsonObject(PROCESS_ATTRIBUTE_NAME).get("max_file_descriptors").getAsLong(); this.diskAvailableBytes = nodeStatsJson.getAsJsonObject("fs").getAsJsonObject("total").get("available_in_bytes").getAsLong(); this.diskTotalBytes = nodeStatsJson.getAsJsonObject("fs").getAsJsonObject("total").get("total_in_bytes").getAsLong(); this.fieldDataCircuitBreakerLimit = nodeStatsJson.getAsJsonObject(BREAKERS_ATTRIBUTE_NAME).getAsJsonObject("fielddata").get("limit_size_in_bytes").getAsLong(); this.fieldDataCircuitBreakerEstimation = nodeStatsJson.getAsJsonObject(BREAKERS_ATTRIBUTE_NAME).getAsJsonObject("fielddata").get("estimated_size_in_bytes").getAsLong(); this.requestCircuitBreakerLimit = nodeStatsJson.getAsJsonObject(BREAKERS_ATTRIBUTE_NAME).getAsJsonObject("request").get("limit_size_in_bytes").getAsLong(); this.requestCircuitBreakerEstimation = nodeStatsJson.getAsJsonObject(BREAKERS_ATTRIBUTE_NAME).getAsJsonObject("request").get("estimated_size_in_bytes").getAsLong(); this.jvmStats = JvmStats.toJvmStats(nodeStatsJson.getAsJsonObject("jvm")); this.indicesStats = IndicesStats.toIndicesStats(nodeStatsJson.getAsJsonObject("indices")); } public static NodeStats toNodeStats(JsonObject jsonObject) { return new NodeStats(jsonObject); } public String getName() { return name; } public String getHost() { return host; } public long getCpuUsage() { return cpuUsage; } public long getOpenFileDescriptors() { return openFileDescriptors; } public long getMaxFileDescriptors() { return maxFileDescriptors; } public long getDiskAvailableBytes() { return diskAvailableBytes; } public long getDiskTotalBytes() { return diskTotalBytes; } public long getFieldDataCircuitBreakerLimit() { return fieldDataCircuitBreakerLimit; } public long getFieldDataCircuitBreakerEstimation() { return fieldDataCircuitBreakerEstimation; } public long getRequestCircuitBreakerLimit() { return requestCircuitBreakerLimit; } public long getRequestCircuitBreakerEstimation() { return requestCircuitBreakerEstimation; } public JvmStats getJvmStats() { return jvmStats; } public IndicesStats getIndicesStats() { return indicesStats; } }
4,405
35.114754
172
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/response/NodeStatsResponse.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.response; import com.google.common.collect.ImmutableList; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.util.List; import java.util.Map; import javax.annotation.concurrent.Immutable; import static com.google.common.collect.ImmutableList.toImmutableList; @Immutable public class NodeStatsResponse { private final ImmutableList<NodeStats> nodeStats; private NodeStatsResponse(JsonObject nodeStatsJson) { this.nodeStats = nodeStatsJson.getAsJsonObject("nodes").entrySet().stream() .map(Map.Entry::getValue) .map(JsonElement::getAsJsonObject) .map(NodeStats::toNodeStats) .collect(toImmutableList()); } public static NodeStatsResponse toNodeStatsResponse(JsonObject jsonObject) { return new NodeStatsResponse(jsonObject); } public List<NodeStats> getNodeStats() { return this.nodeStats; } }
1,753
32.09434
79
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/response/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.es.response; import javax.annotation.ParametersAreNonnullByDefault;
968
39.375
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/searchrequest/NestedFieldTopAggregationDefinition.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.searchrequest; import java.util.Arrays; import java.util.Objects; import javax.annotation.concurrent.Immutable; import org.apache.commons.lang.StringUtils; import org.sonar.server.es.searchrequest.TopAggregationDefinition.NestedFieldFilterScope; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; @Immutable public class NestedFieldTopAggregationDefinition<T> implements TopAggregationDefinition<NestedFieldFilterScope<T>> { private final NestedFieldFilterScope<T> filterScope; private final boolean sticky; public NestedFieldTopAggregationDefinition(String nestedFieldPath, T value, boolean sticky) { requireNonNull(nestedFieldPath, "nestedFieldPath can't be null"); requireNonNull(value, "value can't be null"); checkArgument(StringUtils.countMatches(nestedFieldPath, ".") == 1, "Field path should have only one dot: %s", nestedFieldPath); String[] fullPath = Arrays.stream(StringUtils.split(nestedFieldPath, '.')) .filter(Objects::nonNull) .map(String::trim) .filter(t -> !t.isEmpty()) .toArray(String[]::new); checkArgument(fullPath.length == 2, "field path \"%s\" should have exactly 2 non empty field names, got: %s", nestedFieldPath, Arrays.asList(fullPath)); this.filterScope = new NestedFieldFilterScope<>(fullPath[0], fullPath[1], value); this.sticky = sticky; } @Override public NestedFieldFilterScope<T> getFilterScope() { return filterScope; } @Override public boolean isSticky() { return sticky; } }
2,446
38.467742
122
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/searchrequest/RequestFiltersComputer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.searchrequest; import com.google.common.collect.ImmutableSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.BiPredicate; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.sonar.server.es.searchrequest.TopAggregationDefinition.FilterScope; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static java.util.Objects.requireNonNull; import static java.util.Optional.empty; import static java.util.Optional.of; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; /** * Computes filters of a given ES search request given all the filters to apply and the top-aggregations to include in * the request: * <ul> * <li>the ones for the query (see {@link #computeQueryFilter(AllFiltersImpl, Map) computeQueryFilter})</li> * <li>the ones to apply as post filters (see {@link #computePostFilters(AllFiltersImpl, Set) computePostFilters})</li> * <li>the ones for each top-aggregation (see {@link #getTopAggregationFilter(TopAggregationDefinition) getTopAggregationFilter})</li> * </ul> * <p> * To be able to provide accurate filters, all {@link TopAggregationDefinition} instances for which * {@link #getTopAggregationFilter(TopAggregationDefinition)} may be called, must all be declared in the constructor. */ public class RequestFiltersComputer { private final Set<TopAggregationDefinition<?>> topAggregations; private final Map<FilterNameAndScope, QueryBuilder> postFilters; private final Map<FilterNameAndScope, QueryBuilder> queryFilters; public RequestFiltersComputer(AllFilters allFilters, Set<TopAggregationDefinition<?>> topAggregations) { this.topAggregations = ImmutableSet.copyOf(topAggregations); this.postFilters = computePostFilters((AllFiltersImpl) allFilters, topAggregations); this.queryFilters = computeQueryFilter((AllFiltersImpl) allFilters, postFilters); } public static AllFilters newAllFilters() { return new AllFiltersImpl(); } /** * Any filter of the query which can not be applied to all top-aggregations must be applied as a PostFilter. * <p> * A filter with a given {@link FilterScope} can not be applied to the query when at least one sticky top-aggregation * is enabled which has the same {@link FilterScope}. */ private static Map<FilterNameAndScope, QueryBuilder> computePostFilters(AllFiltersImpl allFilters, Set<TopAggregationDefinition<?>> topAggregations) { Set<FilterScope> enabledStickyTopAggregationtedFieldNames = topAggregations.stream() .filter(TopAggregationDefinition::isSticky) .map(TopAggregationDefinition::getFilterScope) .collect(Collectors.toSet()); // use LinkedHashMap over MoreCollectors.uniqueIndex to preserve order and write UTs more easily Map<FilterNameAndScope, QueryBuilder> res = new LinkedHashMap<>(); allFilters.internalStream() .filter(e -> enabledStickyTopAggregationtedFieldNames.contains(e.getKey().getFilterScope())) .forEach(e -> checkState(res.put(e.getKey(), e.getValue()) == null, "Duplicate: %s", e.getKey())); return res; } /** * Filters which can be applied directly to the query are only the filters which can also be applied to all * aggregations. * <p> * Aggregations are scoped by the filter of the query. If any top-aggregation need to not be applied a filter * (typical case is a filter on the field aggregated to implement sticky facet behavior), this filter can * not be applied to the query and therefor must be applied as PostFilter. */ private static Map<FilterNameAndScope, QueryBuilder> computeQueryFilter(AllFiltersImpl allFilters, Map<FilterNameAndScope, QueryBuilder> postFilters) { Set<FilterNameAndScope> postFilterKeys = postFilters.keySet(); // use LinkedHashMap over MoreCollectors.uniqueIndex to preserve order and write UTs more easily Map<FilterNameAndScope, QueryBuilder> res = new LinkedHashMap<>(); allFilters.internalStream() .filter(e -> !postFilterKeys.contains(e.getKey())) .forEach(e -> checkState(res.put(e.getKey(), e.getValue()) == null, "Duplicate: %s", e.getKey())); return res; } /** * The {@link BoolQueryBuilder} to apply directly to the query in the ES request. * <p> * There could be no filter to apply to the query in the (unexpected but supported) case where all filters * need to be applied as PostFilter because none of them can be applied to all top-aggregations. */ public Optional<BoolQueryBuilder> getQueryFilters() { return toBoolQuery(this.queryFilters, (e, v) -> true); } /** * The {@link BoolQueryBuilder} to add to the ES request as PostFilter * (see {@link org.elasticsearch.action.search.SearchRequestBuilder#setPostFilter(QueryBuilder)}). * <p> * There may be no PostFilter to apply at all. Typical case is when all filters apply to both the query and * all aggregations. (corner case: when there is no filter at all...) */ public Optional<BoolQueryBuilder> getPostFilters() { return toBoolQuery(postFilters, (e, v) -> true); } /** * The {@link BoolQueryBuilder} to apply to the top aggregation for the specified {@link SimpleFieldTopAggregationDefinition}. * <p> * The filter of the aggregations for a top-aggregation will either be: * <ul> * <li>the same as PostFilter, if the top-aggregation is non-sticky or none have the same FilterScope as * {@code topAggregation}</li> * <li>or the same as PostFilter minus any filter which applies to the same {@link FilterScope} of * {@code topAggregation}for the (<strong>if it's sticky</strong>)</li> * </ul> * * @throws IllegalArgumentException if specified {@link TopAggregationDefinition} has not been specified in the constructor */ public Optional<BoolQueryBuilder> getTopAggregationFilter(TopAggregationDefinition<?> topAggregation) { checkArgument(topAggregations.contains(topAggregation), "topAggregation must have been declared in constructor"); return toBoolQuery( postFilters, (e, v) -> !topAggregation.isSticky() || !topAggregation.getFilterScope().intersect(e.getFilterScope())); } private static Optional<BoolQueryBuilder> toBoolQuery(Map<FilterNameAndScope, QueryBuilder> queryFilters, BiPredicate<FilterNameAndScope, QueryBuilder> predicate) { if (queryFilters.isEmpty()) { return empty(); } List<QueryBuilder> selectQueryBuilders = queryFilters.entrySet().stream() .filter(e -> predicate.test(e.getKey(), e.getValue())) .map(Map.Entry::getValue) .toList(); if (selectQueryBuilders.isEmpty()) { return empty(); } BoolQueryBuilder res = boolQuery(); selectQueryBuilders.forEach(res::must); return of(res); } /** * A mean to put together all filters which apply to a given Search request. */ public interface AllFilters { /** * @throws IllegalArgumentException if a filter with the specified name has already been added */ AllFilters addFilter(String name, FilterScope filterScope, @Nullable QueryBuilder filter); Stream<QueryBuilder> stream(); } private static class AllFiltersImpl implements AllFilters { /** * Usage of LinkedHashMap only benefits unit tests by providing predictability of the order of the filters. * ES doesn't care of the order. */ private final Map<FilterNameAndScope, QueryBuilder> filters = new LinkedHashMap<>(); @Override public AllFilters addFilter(String name, FilterScope filterScope, @Nullable QueryBuilder filter) { requireNonNull(name, "name can't be null"); requireNonNull(filterScope, "filterScope can't be null"); if (filter == null) { return this; } checkArgument( filters.put(new FilterNameAndScope(name, filterScope), filter) == null, "A filter with name %s has already been added", name); return this; } @Override public Stream<QueryBuilder> stream() { return filters.values().stream(); } private Stream<Map.Entry<FilterNameAndScope, QueryBuilder>> internalStream() { return filters.entrySet().stream(); } } /** * Serves as a key in internal map of filters, it behaves the same as if the filterName was directly used as a key in * this map but also holds the name of the field each filter applies to. * <p> * This saves from using two internal maps. */ @Immutable private static final class FilterNameAndScope { private final String filterName; private final FilterScope filterScope; private FilterNameAndScope(String filterName, FilterScope filterScope) { this.filterName = filterName; this.filterScope = filterScope; } public FilterScope getFilterScope() { return filterScope; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FilterNameAndScope that = (FilterNameAndScope) o; return filterName.equals(that.filterName); } @Override public int hashCode() { return Objects.hash(filterName); } } }
10,468
39.735409
138
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/searchrequest/SimpleFieldTopAggregationDefinition.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.searchrequest; import javax.annotation.concurrent.Immutable; import org.sonar.server.es.searchrequest.TopAggregationDefinition.FilterScope; import static java.util.Objects.requireNonNull; /** * Implementation of {@link TopAggregationDefinition} with a filter scope for a simple field. */ @Immutable public final class SimpleFieldTopAggregationDefinition implements TopAggregationDefinition<FilterScope> { private final FilterScope filterScope; private final boolean sticky; public SimpleFieldTopAggregationDefinition(String fieldName, boolean sticky) { requireNonNull(fieldName, "fieldName can't be null"); this.filterScope = new SimpleFieldFilterScope(fieldName); this.sticky = sticky; } @Override public FilterScope getFilterScope() { return filterScope; } @Override public boolean isSticky() { return sticky; } }
1,736
32.403846
105
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/searchrequest/SubAggregationHelper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.searchrequest; import java.util.Arrays; import java.util.Objects; import java.util.Optional; import java.util.stream.Collector; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.elasticsearch.search.aggregations.AbstractAggregationBuilder; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.BucketOrder; import org.elasticsearch.search.aggregations.bucket.terms.IncludeExclude; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import org.sonar.server.es.EsUtils; import org.sonar.server.es.Facets; import static java.lang.Math.max; import static java.util.Optional.of; public class SubAggregationHelper { private static final int TERM_AGGREGATION_MIN_DOC_COUNT = 1; private static final BucketOrder ORDER_BY_BUCKET_SIZE_DESC = BucketOrder.count(false); /** In some cases the user selects >15 items for one facet. In that case, we want to calculate the doc count for all of them (not just the first 15 items, which would be the * default for the TermsAggregation). */ private static final int MAXIMUM_NUMBER_OF_SELECTED_ITEMS_WHOSE_DOC_COUNT_WILL_BE_CALCULATED = 50; private static final Collector<CharSequence, ?, String> PIPE_JOINER = Collectors.joining("|"); @CheckForNull private final AbstractAggregationBuilder<?> subAggregation; private final BucketOrder order; public SubAggregationHelper() { this(null, null); } public SubAggregationHelper(@Nullable AbstractAggregationBuilder<?> subAggregation) { this(subAggregation, null); } public SubAggregationHelper(@Nullable AbstractAggregationBuilder<?> subAggregation, @Nullable BucketOrder order) { this.subAggregation = subAggregation; this.order = order == null ? ORDER_BY_BUCKET_SIZE_DESC : order; } public TermsAggregationBuilder buildTermsAggregation(String name, TopAggregationDefinition<?> topAggregation, @Nullable Integer numberOfTerms) { TermsAggregationBuilder termsAggregation = AggregationBuilders.terms(name) .field(topAggregation.getFilterScope().getFieldName()) .order(order) .minDocCount(TERM_AGGREGATION_MIN_DOC_COUNT); if (numberOfTerms != null) { termsAggregation.size(numberOfTerms); } if (subAggregation != null) { termsAggregation = termsAggregation.subAggregation(subAggregation); } return termsAggregation; } public <T> Optional<TermsAggregationBuilder> buildSelectedItemsAggregation(String name, TopAggregationDefinition<?> topAggregation, T[] selected) { if (selected.length <= 0) { return Optional.empty(); } String includes = Arrays.stream(selected) .filter(Objects::nonNull) .map(s -> EsUtils.escapeSpecialRegexChars(s.toString())) .collect(PIPE_JOINER); TermsAggregationBuilder selectedTerms = AggregationBuilders.terms(name + Facets.SELECTED_SUB_AGG_NAME_SUFFIX) .size(max(MAXIMUM_NUMBER_OF_SELECTED_ITEMS_WHOSE_DOC_COUNT_WILL_BE_CALCULATED, includes.length())) .field(topAggregation.getFilterScope().getFieldName()) .includeExclude(new IncludeExclude(includes, null)); if (subAggregation != null) { selectedTerms = selectedTerms.subAggregation(subAggregation); } return of(selectedTerms); } }
4,213
40.722772
175
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/searchrequest/TopAggregationDefinition.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.searchrequest; import java.util.Objects; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import static java.util.Objects.requireNonNull; /** * Models a first level aggregation in an Elasticsearch request (aka. top-aggregation) with a specific * {@link FilterScope} and whether it is to be used to compute data for a sticky facet (see {@link #isSticky()}) or not. */ public interface TopAggregationDefinition<S extends TopAggregationDefinition.FilterScope> { boolean STICKY = true; boolean NON_STICKY = false; S getFilterScope(); boolean isSticky(); abstract class FilterScope { public abstract String getFieldName(); /** * All implementations must implement {@link Object#equals(Object)} and {@link Object#hashCode()} to be used * in {@link java.util.Set}. */ public abstract boolean equals(Object other); public abstract int hashCode(); /** * */ public abstract boolean intersect(@Nullable FilterScope other); } /** * Filter applies to a regular first level field. */ @Immutable final class SimpleFieldFilterScope extends FilterScope { private final String fieldName; public SimpleFieldFilterScope(String fieldName) { this.fieldName = requireNonNull(fieldName, "fieldName can't be null"); } @Override public String getFieldName() { return fieldName; } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SimpleFieldFilterScope that = (SimpleFieldFilterScope) o; return fieldName.equals(that.fieldName); } @Override public int hashCode() { return Objects.hash(fieldName); } @Override public boolean intersect(@Nullable FilterScope other) { if (this == other) { return true; } if (other == null) { return false; } return fieldName.equals(other.getFieldName()); } } /** * Filter applies to a first level field holding an array of objects (aka. nested fields) used to store various data * with similar structure in a single field. Each data is identified by a dedicated field which holds a different value * for each data: eg. metric key subfield identifies which metric the other subfield(s) are the value of. * <p> * This filter scope allows to represent filtering on each type of data in this first-level field, hence the necessity * to provide both the name of the subfield and the value which identifies that data. */ @Immutable final class NestedFieldFilterScope<T> extends FilterScope { private final String fieldName; private final String nestedFieldName; private final T value; public NestedFieldFilterScope(String fieldName, String nestedFieldName, T value) { this.fieldName = requireNonNull(fieldName, "fieldName can't be null"); this.nestedFieldName = requireNonNull(nestedFieldName, "nestedFieldName can't be null"); this.value = requireNonNull(value, "value can't be null"); } @Override public String getFieldName() { return fieldName; } public String getNestedFieldName() { return nestedFieldName; } public T getNestedFieldValue() { return value; } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NestedFieldFilterScope<?> that = (NestedFieldFilterScope<?>) o; return fieldName.equals(that.fieldName) && nestedFieldName.equals(that.nestedFieldName) && value.equals(that.value); } @Override public int hashCode() { return Objects.hash(fieldName, nestedFieldName, value); } @Override public boolean intersect(@Nullable FilterScope other) { if (other instanceof NestedFieldFilterScope) { return equals(other); } return false; } } }
4,968
29.484663
121
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/searchrequest/TopAggregationHelper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.searchrequest; import java.util.function.Consumer; import javax.annotation.Nullable; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder; import static com.google.common.base.Preconditions.checkState; public class TopAggregationHelper { public static final Consumer<BoolQueryBuilder> NO_EXTRA_FILTER = t -> { }; public static final Consumer<FilterAggregationBuilder> NO_OTHER_SUBAGGREGATION = t -> { }; private final RequestFiltersComputer filterComputer; private final SubAggregationHelper subAggregationHelper; public TopAggregationHelper(RequestFiltersComputer filterComputer, SubAggregationHelper subAggregationHelper) { this.filterComputer = filterComputer; this.subAggregationHelper = subAggregationHelper; } /** * Creates a top-level aggregation that will be correctly scoped (ie. filtered) to aggregate on * {@code TopAggregationDefinition#getFieldName} given the Request filters and the other top-aggregations * (see {@link RequestFiltersComputer#getTopAggregationFilter(TopAggregationDefinition)}). * <p> * Optionally, the scope (ie. filter) of the aggregation can be further reduced by providing {@code extraFilters}. * <p> * Aggregations <strong>must</strong> be added to the top-level one by providing {@code subAggregations} otherwise * the aggregation will be empty and will yield no result. * * @param topAggregationName the name of the top-aggregation in the request * @param topAggregation properties of the top-aggregation * @param extraFilters optional extra filters which could further restrict the scope of computation of the * top-terms aggregation * @param subAggregations sub aggregation(s) to actually compute something * * @throws IllegalStateException if no sub-aggregation has been added * @return the aggregation, that can be added on top level of the elasticsearch request */ public FilterAggregationBuilder buildTopAggregation(String topAggregationName, TopAggregationDefinition<?> topAggregation, Consumer<BoolQueryBuilder> extraFilters, Consumer<FilterAggregationBuilder> subAggregations) { BoolQueryBuilder filter = filterComputer.getTopAggregationFilter(topAggregation) .orElseGet(QueryBuilders::boolQuery); // optionally add extra filter(s) extraFilters.accept(filter); FilterAggregationBuilder res = AggregationBuilders.filter(topAggregationName, filter); subAggregations.accept(res); checkState( !res.getSubAggregations().isEmpty(), "no sub-aggregation has been added to top-aggregation %s", topAggregationName); return res; } /** * Same as {@link #buildTopAggregation(String, TopAggregationDefinition, Consumer, Consumer)} with built-in addition of a * top-term sub aggregation based field defined by {@link TopAggregationDefinition.FilterScope#getFieldName()} of * {@link TopAggregationDefinition#getFilterScope()}. */ public FilterAggregationBuilder buildTermTopAggregation( String topAggregationName, TopAggregationDefinition<?> topAggregation, @Nullable Integer numberOfTerms, Consumer<BoolQueryBuilder> extraFilters, Consumer<FilterAggregationBuilder> otherSubAggregations ) { Consumer<FilterAggregationBuilder> subAggregations = t -> { t.subAggregation(subAggregationHelper.buildTermsAggregation(topAggregationName, topAggregation, numberOfTerms)); otherSubAggregations.accept(t); }; return buildTopAggregation(topAggregationName, topAggregation, extraFilters, subAggregations); } public SubAggregationHelper getSubAggregationHelper() { return subAggregationHelper; } }
4,728
44.912621
124
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/searchrequest/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.es.searchrequest; import javax.annotation.ParametersAreNonnullByDefault;
973
39.583333
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/textsearch/ComponentTextSearchFeature.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.textsearch; import java.util.stream.Stream; import org.elasticsearch.index.query.QueryBuilder; import org.sonar.server.es.textsearch.ComponentTextSearchQueryFactory.ComponentTextSearchQuery; public interface ComponentTextSearchFeature { enum UseCase { GENERATE_RESULTS, CHANGE_ORDER_OF_RESULTS } default UseCase getUseCase() { return UseCase.GENERATE_RESULTS; } default Stream<QueryBuilder> getQueries(ComponentTextSearchQuery query) { return Stream.of(getQuery(query)); } QueryBuilder getQuery(ComponentTextSearchQuery query); }
1,433
33.142857
95
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/textsearch/ComponentTextSearchFeatureRepertoire.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.textsearch; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Stream; import org.apache.commons.lang.StringUtils; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.MatchQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.sonar.server.es.newindex.DefaultIndexSettings; import org.sonar.server.es.newindex.DefaultIndexSettingsElement; import org.sonar.server.es.textsearch.ComponentTextSearchQueryFactory.ComponentTextSearchQuery; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import static org.elasticsearch.index.query.QueryBuilders.matchQuery; import static org.elasticsearch.index.query.QueryBuilders.termsQuery; import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.SEARCH_GRAMS_ANALYZER; import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.SEARCH_PREFIX_ANALYZER; import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.SEARCH_PREFIX_CASE_INSENSITIVE_ANALYZER; import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.SORTABLE_ANALYZER; import static org.sonar.server.es.textsearch.ComponentTextSearchFeature.UseCase.CHANGE_ORDER_OF_RESULTS; import static org.sonar.server.es.textsearch.ComponentTextSearchFeature.UseCase.GENERATE_RESULTS; public enum ComponentTextSearchFeatureRepertoire implements ComponentTextSearchFeature { EXACT_IGNORE_CASE(CHANGE_ORDER_OF_RESULTS) { @Override public QueryBuilder getQuery(ComponentTextSearchQuery query) { return matchQuery(SORTABLE_ANALYZER.subField(query.getFieldName()), query.getQueryText()) .boost(2.5F); } }, PREFIX(CHANGE_ORDER_OF_RESULTS) { @Override public Stream<QueryBuilder> getQueries(ComponentTextSearchQuery query) { List<String> tokens = query.getQueryTextTokens(); if (tokens.isEmpty()) { return Stream.empty(); } BoolQueryBuilder queryBuilder = prefixAndPartialQuery(tokens, query.getFieldName(), SEARCH_PREFIX_ANALYZER) .boost(3F); return Stream.of(queryBuilder); } }, PREFIX_IGNORE_CASE(GENERATE_RESULTS) { @Override public Stream<QueryBuilder> getQueries(ComponentTextSearchQuery query) { List<String> tokens = query.getQueryTextTokens(); if (tokens.isEmpty()) { return Stream.empty(); } List<String> lowerCaseTokens = tokens.stream().map(t -> t.toLowerCase(Locale.ENGLISH)).toList(); BoolQueryBuilder queryBuilder = prefixAndPartialQuery(lowerCaseTokens, query.getFieldName(), SEARCH_PREFIX_CASE_INSENSITIVE_ANALYZER) .boost(2F); return Stream.of(queryBuilder); } }, PARTIAL(GENERATE_RESULTS) { @Override public Stream<QueryBuilder> getQueries(ComponentTextSearchQuery query) { List<String> tokens = query.getQueryTextTokens(); if (tokens.isEmpty()) { return Stream.empty(); } BoolQueryBuilder queryBuilder = boolQuery().boost(0.5F); tokens.stream() .map(text -> tokenQuery(text, query.getFieldName(), SEARCH_GRAMS_ANALYZER)) .forEach(queryBuilder::must); return Stream.of(queryBuilder); } }, KEY(GENERATE_RESULTS) { @Override public QueryBuilder getQuery(ComponentTextSearchQuery query) { return matchQuery(SORTABLE_ANALYZER.subField(query.getFieldKey()), query.getQueryText()) .boost(50F); } }, RECENTLY_BROWSED(CHANGE_ORDER_OF_RESULTS) { @Override public Stream<QueryBuilder> getQueries(ComponentTextSearchQuery query) { Set<String> recentlyBrowsedKeys = query.getRecentlyBrowsedKeys(); if (recentlyBrowsedKeys.isEmpty()) { return Stream.empty(); } return Stream.of(termsQuery(query.getFieldKey(), recentlyBrowsedKeys).boost(100F)); } }, FAVORITE(CHANGE_ORDER_OF_RESULTS) { @Override public Stream<QueryBuilder> getQueries(ComponentTextSearchQuery query) { Set<String> favoriteKeys = query.getFavoriteKeys(); if (favoriteKeys.isEmpty()) { return Stream.empty(); } return Stream.of(termsQuery(query.getFieldKey(), favoriteKeys).boost(1000F)); } }; private final UseCase useCase; ComponentTextSearchFeatureRepertoire(UseCase useCase) { this.useCase = useCase; } @Override public QueryBuilder getQuery(ComponentTextSearchQuery query) { throw new UnsupportedOperationException(); } protected BoolQueryBuilder prefixAndPartialQuery(List<String> tokens, String originalFieldName, DefaultIndexSettingsElement analyzer) { BoolQueryBuilder queryBuilder = boolQuery(); AtomicBoolean first = new AtomicBoolean(true); tokens.stream() .map(queryTerm -> { if (first.getAndSet(false)) { return tokenQuery(queryTerm, originalFieldName, analyzer); } return tokenQuery(queryTerm, originalFieldName, SEARCH_GRAMS_ANALYZER); }) .forEach(queryBuilder::must); return queryBuilder; } protected MatchQueryBuilder tokenQuery(String queryTerm, String fieldName, DefaultIndexSettingsElement analyzer) { // We will truncate the search to the maximum length of nGrams in the index. // Otherwise the search would for sure not find any results. String truncatedQuery = StringUtils.left(queryTerm, DefaultIndexSettings.MAXIMUM_NGRAM_LENGTH); return matchQuery(analyzer.subField(fieldName), truncatedQuery); } @Override public UseCase getUseCase() { return useCase; } }
6,422
39.14375
139
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/textsearch/ComponentTextSearchQueryFactory.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.textsearch; import com.google.common.collect.ImmutableSet; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.sonar.server.es.textsearch.ComponentTextSearchFeature.UseCase; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import static org.sonar.server.es.textsearch.JavaTokenizer.split; /** * This class is used in order to do some advanced full text search in an index on component key and component name * * The index must contains at least one field for the component key and one field for the component name */ public class ComponentTextSearchQueryFactory { private ComponentTextSearchQueryFactory() { // Only static methods } public static QueryBuilder createQuery(ComponentTextSearchQuery query, ComponentTextSearchFeature... features) { checkArgument(features.length > 0, "features cannot be empty"); BoolQueryBuilder esQuery = boolQuery().must( createQuery(query, features, UseCase.GENERATE_RESULTS) .orElseThrow(() -> new IllegalStateException("No text search features found to generate search results. Features: " + Arrays.toString(features)))); createQuery(query, features, UseCase.CHANGE_ORDER_OF_RESULTS) .ifPresent(esQuery::should); return esQuery; } private static Optional<QueryBuilder> createQuery(ComponentTextSearchQuery query, ComponentTextSearchFeature[] features, UseCase useCase) { BoolQueryBuilder generateResults = boolQuery(); Arrays.stream(features) .filter(f -> f.getUseCase() == useCase) .flatMap(f -> f.getQueries(query)) .forEach(generateResults::should); if (!generateResults.should().isEmpty()) { return Optional.of(generateResults); } else { return Optional.empty(); } } public static class ComponentTextSearchQuery { private final String queryText; private final List<String> queryTextTokens; private final String fieldKey; private final String fieldName; private final Set<String> recentlyBrowsedKeys; private final Set<String> favoriteKeys; private ComponentTextSearchQuery(Builder builder) { this.queryText = builder.queryText; this.queryTextTokens = split(builder.queryText); this.fieldKey = builder.fieldKey; this.fieldName = builder.fieldName; this.recentlyBrowsedKeys = builder.recentlyBrowsedKeys; this.favoriteKeys = builder.favoriteKeys; } public String getQueryText() { return queryText; } public List<String> getQueryTextTokens() { return queryTextTokens; } public String getFieldKey() { return fieldKey; } public String getFieldName() { return fieldName; } public Set<String> getRecentlyBrowsedKeys() { return recentlyBrowsedKeys; } public static Builder builder() { return new Builder(); } public Set<String> getFavoriteKeys() { return favoriteKeys; } public static class Builder { private String queryText; private String fieldKey; private String fieldName; private Set<String> recentlyBrowsedKeys = Collections.emptySet(); private Set<String> favoriteKeys = Collections.emptySet(); /** * The text search query */ public Builder setQueryText(String queryText) { this.queryText = queryText; return this; } /** * The index field that contains the component key */ public Builder setFieldKey(String fieldKey) { this.fieldKey = fieldKey; return this; } /** * The index field that contains the component name */ public Builder setFieldName(String fieldName) { this.fieldName = fieldName; return this; } /** * Component keys of recently browsed items */ public Builder setRecentlyBrowsedKeys(Set<String> recentlyBrowsedKeys) { this.recentlyBrowsedKeys = ImmutableSet.copyOf(recentlyBrowsedKeys); return this; } /** * Component keys of favorite items */ public Builder setFavoriteKeys(Set<String> favoriteKeys) { this.favoriteKeys = ImmutableSet.copyOf(favoriteKeys); return this; } public ComponentTextSearchQuery build() { requireNonNull(queryText, "query text cannot be null"); requireNonNull(fieldKey, "field key cannot be null"); requireNonNull(fieldName, "field name cannot be null"); requireNonNull(recentlyBrowsedKeys, "field recentlyBrowsedKeys cannot be null"); requireNonNull(favoriteKeys, "field favoriteKeys cannot be null"); return new ComponentTextSearchQuery(this); } } } }
5,868
32.729885
155
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/textsearch/JavaTokenizer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.es.textsearch; import java.util.Arrays; import java.util.List; import org.apache.commons.lang.StringUtils; import org.sonar.server.es.newindex.DefaultIndexSettings; import static org.sonar.server.es.newindex.DefaultIndexSettings.MINIMUM_NGRAM_LENGTH; /** * Splits text queries into their tokens, for to use them in n_gram match queries later. */ public class JavaTokenizer { private JavaTokenizer() { // use static methods } public static List<String> split(String queryText) { return Arrays.stream( queryText.split(DefaultIndexSettings.SEARCH_TERM_TOKENIZER_PATTERN)) .filter(StringUtils::isNotEmpty) .filter(s -> s.length() >= MINIMUM_NGRAM_LENGTH) .toList(); } }
1,581
33.391304
88
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/es/textsearch/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.es.textsearch; import javax.annotation.ParametersAreNonnullByDefault;
971
37.88
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/extension/CoreExtensionBootstraper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.extension; import java.util.List; import org.sonar.api.platform.Server; import org.sonar.api.platform.ServerStartHandler; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.api.utils.log.Profiler; import org.sonar.core.platform.SpringComponentContainer; import static java.lang.String.format; /** * Startup task responsible to bootstrap installed Core Extensions (if any). */ public class CoreExtensionBootstraper implements ServerStartHandler { private static final Logger LOGGER = Loggers.get(CoreExtensionBootstraper.class); private final SpringComponentContainer componentContainer; public CoreExtensionBootstraper(SpringComponentContainer componentContainer) { this.componentContainer = componentContainer; } @Override public void onServerStart(Server server) { List<CoreExtensionBridge> bridges = componentContainer.getComponentsByType(CoreExtensionBridge.class); for (CoreExtensionBridge bridge : bridges) { Profiler profiler = Profiler.create(LOGGER).startInfo(format("Bootstrapping %s", bridge.getPluginName())); bridge.startPlugin(componentContainer); profiler.stopInfo(); } } }
2,059
36.454545
112
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/extension/CoreExtensionBridge.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.extension; import org.sonar.core.platform.SpringComponentContainer; /** * Interface implemented by the Extension point exposed by the Core Extensions that serves as the unique access * point from the whole SQ instance into the Core Extension. */ public interface CoreExtensionBridge { String getPluginName(); /** * Bootstraps the plugin. * * @param parent the parent SpringComponentContainer which provides Platform components for the Privileged plugin to use. * * @throws IllegalStateException if called more than once */ void startPlugin(SpringComponentContainer parent); /** * This method is called when Platform is shutting down. */ void stopPlugin(); }
1,569
32.404255
123
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/extension/CoreExtensionStopper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.extension; import java.util.List; import org.sonar.api.Startable; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.api.utils.log.Profiler; import org.sonar.core.platform.Container; import static java.lang.String.format; /** * As an component of PlatformLevel4, this class is responsible for notifying shutdown to the installed Core Extensions * (if any). */ public class CoreExtensionStopper implements Startable { private static final Logger LOGGER = Loggers.get(CoreExtensionStopper.class); private final Container platformContainer; public CoreExtensionStopper(Container platformContainer) { this.platformContainer = platformContainer; } @Override public void start() { // nothing to do, privileged plugins are started by CoreExtensionBootstraper } @Override public void stop() { List<CoreExtensionBridge> bridges = platformContainer.getComponentsByType(CoreExtensionBridge.class); for (CoreExtensionBridge bridge : bridges) { Profiler profiler = Profiler.create(LOGGER).startInfo(format("Stopping %s", bridge.getPluginName())); bridge.stopPlugin(); profiler.stopInfo(); } } }
2,063
33.983051
119
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/extension/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.extension; import javax.annotation.ParametersAreNonnullByDefault;
967
37.72
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/favorite/FavoriteUpdater.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.favorite; import java.util.List; import javax.annotation.Nullable; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.entity.EntityDto; import org.sonar.db.property.PropertyDto; import org.sonar.db.property.PropertyQuery; import static com.google.common.base.Preconditions.checkArgument; public class FavoriteUpdater { static final String PROP_FAVORITE_KEY = "favourite"; private final DbClient dbClient; public FavoriteUpdater(DbClient dbClient) { this.dbClient = dbClient; } /** * Set favorite to the logged in user. If no user, no action is done */ public void add(DbSession dbSession, EntityDto entity, @Nullable String userUuid, @Nullable String userLogin, boolean failIfTooManyFavorites) { if (userUuid == null) { return; } List<PropertyDto> existingFavoriteOnComponent = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder() .setKey(PROP_FAVORITE_KEY) .setUserUuid(userUuid) .setEntityUuid(entity.getUuid()) .build(), dbSession); checkArgument(existingFavoriteOnComponent.isEmpty(), "Component '%s' (uuid: %s) is already a favorite", entity.getKey(), entity.getUuid()); List<PropertyDto> existingFavorites = dbClient.propertiesDao().selectEntityPropertyByKeyAndUserUuid(dbSession, PROP_FAVORITE_KEY, userUuid); if (existingFavorites.size() >= 100) { checkArgument(!failIfTooManyFavorites, "You cannot have more than 100 favorites on components with qualifier '%s'", entity.getQualifier()); return; } dbClient.propertiesDao().saveProperty(dbSession, new PropertyDto() .setKey(PROP_FAVORITE_KEY) .setEntityUuid(entity.getUuid()) .setUserUuid(userUuid), userLogin, entity.getKey(), entity.getName(), entity.getQualifier()); } /** * Remove a favorite to the user. * * @throws IllegalArgumentException if the component is not a favorite */ public void remove(DbSession dbSession, EntityDto entity, @Nullable String userUuid, @Nullable String userLogin) { if (userUuid == null) { return; } int result = dbClient.propertiesDao().delete(dbSession, new PropertyDto() .setKey(PROP_FAVORITE_KEY) .setEntityUuid(entity.getUuid()) .setUserUuid(userUuid), userLogin, entity.getKey(), entity.getName(), entity.getQualifier()); checkArgument(result == 1, "Component '%s' (uuid: %s) is not a favorite", entity.getKey(), entity.getUuid()); } }
3,354
37.563218
145
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/favorite/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.favorite; import javax.annotation.ParametersAreNonnullByDefault;
966
37.68
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/feature/SonarQubeFeature.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.feature; public interface SonarQubeFeature { String getName(); boolean isAvailable(); }
963
33.428571
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/feature/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.feature; import javax.annotation.ParametersAreNonnullByDefault;
964
39.208333
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/IssueFieldsSetter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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; import com.google.common.base.Joiner; import java.time.temporal.ChronoUnit; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.rules.RuleType; import org.sonar.api.server.ServerSide; import org.sonar.api.server.rule.RuleTagFormat; import org.sonar.api.utils.Duration; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.DefaultIssueComment; import org.sonar.core.issue.IssueChangeContext; import org.sonar.db.protobuf.DbIssues; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserIdDto; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Strings.isNullOrEmpty; /** * Updates issue fields and chooses if changes must be kept in history. */ @ServerSide @ComputeEngineSide public class IssueFieldsSetter { public static final String UNUSED = ""; public static final String SEVERITY = "severity"; public static final String TYPE = "type"; public static final String ASSIGNEE = "assignee"; public static final String RESOLUTION = "resolution"; public static final String STATUS = "status"; public static final String AUTHOR = "author"; public static final String FILE = "file"; public static final String FROM_BRANCH = "from_branch"; /** * It should be renamed to 'effort', but it hasn't been done to prevent a massive update in database */ public static final String TECHNICAL_DEBT = "technicalDebt"; public static final String LINE = "line"; public static final String TAGS = "tags"; public static final String CODE_VARIANTS = "code_variants"; private static final Joiner CHANGELOG_LIST_JOINER = Joiner.on(" ").skipNulls(); public boolean setType(DefaultIssue issue, RuleType type, IssueChangeContext context) { if (!Objects.equals(type, issue.type())) { issue.setFieldChange(context, TYPE, issue.type(), type); issue.setType(type); issue.setUpdateDate(context.date()); issue.setChanged(true); return true; } return false; } public boolean setSeverity(DefaultIssue issue, String severity, IssueChangeContext context) { checkState(!issue.manualSeverity(), "Severity can't be changed"); if (!Objects.equals(severity, issue.severity())) { issue.setFieldChange(context, SEVERITY, issue.severity(), severity); issue.setSeverity(severity); issue.setUpdateDate(context.date()); issue.setChanged(true); return true; } return false; } public boolean setPastSeverity(DefaultIssue issue, @Nullable String previousSeverity, IssueChangeContext context) { String currentSeverity = issue.severity(); issue.setSeverity(previousSeverity); return setSeverity(issue, currentSeverity, context); } public boolean setManualSeverity(DefaultIssue issue, String severity, IssueChangeContext context) { if (!issue.manualSeverity() || !Objects.equals(severity, issue.severity())) { issue.setFieldChange(context, SEVERITY, issue.severity(), severity); issue.setSeverity(severity); issue.setManualSeverity(true); issue.setUpdateDate(context.date()); issue.setChanged(true); issue.setSendNotifications(true); return true; } return false; } public boolean assign(DefaultIssue issue, @Nullable UserDto user, IssueChangeContext context) { String assigneeUuid = user != null ? user.getUuid() : null; if (!Objects.equals(assigneeUuid, issue.assignee())) { String newAssigneeName = user == null ? null : user.getName(); issue.setFieldChange(context, ASSIGNEE, UNUSED, newAssigneeName); issue.setAssigneeUuid(user != null ? user.getUuid() : null); issue.setUpdateDate(context.date()); issue.setChanged(true); issue.setSendNotifications(true); return true; } return false; } /** * Used to set the assignee when it was null */ public boolean setNewAssignee(DefaultIssue issue, @Nullable UserIdDto userId, IssueChangeContext context) { if (userId == null) { return false; } checkState(issue.assignee() == null, "It's not possible to update the assignee with this method, please use assign()"); issue.setFieldChange(context, ASSIGNEE, UNUSED, userId.getUuid()); issue.setAssigneeUuid(userId.getUuid()); issue.setAssigneeLogin(userId.getLogin()); issue.setUpdateDate(context.date()); issue.setChanged(true); issue.setSendNotifications(true); return true; } public boolean unsetLine(DefaultIssue issue, IssueChangeContext context) { Integer currentValue = issue.line(); if (currentValue != null) { issue.setFieldChange(context, LINE, currentValue, ""); issue.setLine(null); issue.setChanged(true); return true; } return false; } public boolean setPastLine(DefaultIssue issue, @Nullable Integer previousLine) { Integer currentLine = issue.line(); issue.setLine(previousLine); if (!Objects.equals(currentLine, previousLine)) { issue.setLine(currentLine); issue.setChanged(true); return true; } return false; } public boolean setRuleDescriptionContextKey(DefaultIssue issue, @Nullable String previousContextKey) { String currentContextKey = issue.getRuleDescriptionContextKey().orElse(null); issue.setRuleDescriptionContextKey(previousContextKey); if (!Objects.equals(currentContextKey, previousContextKey)) { issue.setRuleDescriptionContextKey(currentContextKey); issue.setChanged(true); return true; } return false; } /** * New value will be set if the locations are different, ignoring the hashes. If that's the case, we mark the issue as changed, * and we also flag that the locations have changed, so that we calculate all the hashes later, in an efficient way. * WARNING: It is possible that the hashes changes without the text ranges changing, but for optimization we take that risk. * * @see ComputeLocationHashesVisitor */ public boolean setLocations(DefaultIssue issue, @Nullable Object locations) { if (!locationsEqualsIgnoreHashes(locations, issue.getLocations())) { issue.setLocations(locations); issue.setChanged(true); issue.setLocationsChanged(true); return true; } return false; } private static boolean locationsEqualsIgnoreHashes(@Nullable Object l1, @Nullable DbIssues.Locations l2) { if (l1 == null && l2 == null) { return true; } if (l2 == null || !(l1 instanceof DbIssues.Locations)) { return false; } DbIssues.Locations l1c = (DbIssues.Locations) l1; if (!Objects.equals(l1c.getTextRange(), l2.getTextRange()) || l1c.getFlowCount() != l2.getFlowCount()) { return false; } for (int i = 0; i < l1c.getFlowCount(); i++) { if (l1c.getFlow(i).getLocationCount() != l2.getFlow(i).getLocationCount()) { return false; } for (int j = 0; j < l1c.getFlow(i).getLocationCount(); j++) { if (!locationEqualsIgnoreHashes(l1c.getFlow(i).getLocation(j), l2.getFlow(i).getLocation(j))) { return false; } } } return true; } private static boolean locationEqualsIgnoreHashes(DbIssues.Location l1, DbIssues.Location l2) { return Objects.equals(l1.getComponentId(), l2.getComponentId()) && Objects.equals(l1.getTextRange(), l2.getTextRange()) && Objects.equals(l1.getMsg(), l2.getMsg()); } public boolean setPastLocations(DefaultIssue issue, @Nullable Object previousLocations) { Object currentLocations = issue.getLocations(); issue.setLocations(previousLocations); return setLocations(issue, currentLocations); } public boolean setResolution(DefaultIssue issue, @Nullable String resolution, IssueChangeContext context) { if (!Objects.equals(resolution, issue.resolution())) { issue.setFieldChange(context, RESOLUTION, issue.resolution(), resolution); issue.setResolution(resolution); issue.setUpdateDate(context.date()); issue.setChanged(true); issue.setSendNotifications(true); return true; } return false; } public boolean setStatus(DefaultIssue issue, String status, IssueChangeContext context) { if (!Objects.equals(status, issue.status())) { issue.setFieldChange(context, STATUS, issue.status(), status); issue.setStatus(status); issue.setUpdateDate(context.date()); issue.setChanged(true); issue.setSendNotifications(true); return true; } return false; } public boolean setAuthorLogin(DefaultIssue issue, @Nullable String authorLogin, IssueChangeContext context) { if (!Objects.equals(authorLogin, issue.authorLogin())) { issue.setFieldChange(context, AUTHOR, issue.authorLogin(), authorLogin); issue.setAuthorLogin(authorLogin); issue.setUpdateDate(context.date()); issue.setChanged(true); // do not send notifications to prevent spam when installing the developer cockpit plugin return true; } return false; } /** * Used to set the author when it was null */ public boolean setNewAuthor(DefaultIssue issue, @Nullable String newAuthorLogin, IssueChangeContext context) { if (isNullOrEmpty(newAuthorLogin)) { return false; } checkState(issue.authorLogin() == null, "It's not possible to update the author with this method, please use setAuthorLogin()"); issue.setFieldChange(context, AUTHOR, null, newAuthorLogin); issue.setAuthorLogin(newAuthorLogin); issue.setUpdateDate(context.date()); issue.setChanged(true); // do not send notifications to prevent spam when installing the developer cockpit plugin return true; } public boolean setMessage(DefaultIssue issue, @Nullable String s, IssueChangeContext context) { if (!Objects.equals(s, issue.message())) { issue.setMessage(s); issue.setUpdateDate(context.date()); issue.setChanged(true); return true; } return false; } public boolean setMessageFormattings(DefaultIssue issue, @Nullable Object issueMessageFormattings, IssueChangeContext context) { if (!messageFormattingsEqualsIgnoreHashes(issueMessageFormattings, issue.getMessageFormattings())) { issue.setMessageFormattings(issueMessageFormattings); issue.setUpdateDate(context.date()); issue.setChanged(true); return true; } return false; } private static boolean messageFormattingsEqualsIgnoreHashes(@Nullable Object l1, @Nullable DbIssues.MessageFormattings l2) { if (l1 == null && l2 == null) { return true; } if (l2 == null || !(l1 instanceof DbIssues.MessageFormattings)) { return false; } DbIssues.MessageFormattings l1c = (DbIssues.MessageFormattings) l1; if (!Objects.equals(l1c.getMessageFormattingCount(), l2.getMessageFormattingCount())) { return false; } for (int i = 0; i < l1c.getMessageFormattingCount(); i++) { if (l1c.getMessageFormatting(i).getStart() != l2.getMessageFormatting(i).getStart() || l1c.getMessageFormatting(i).getEnd() != l2.getMessageFormatting(i).getEnd() || l1c.getMessageFormatting(i).getType() != l2.getMessageFormatting(i).getType()) { return false; } } return true; } public boolean setPastMessage(DefaultIssue issue, @Nullable String previousMessage, @Nullable Object previousMessageFormattings, IssueChangeContext context) { String currentMessage = issue.message(); DbIssues.MessageFormattings currentMessageFormattings = issue.getMessageFormattings(); issue.setMessage(previousMessage); issue.setMessageFormattings(previousMessageFormattings); boolean changed = setMessage(issue, currentMessage, context); return setMessageFormattings(issue, currentMessageFormattings, context) || changed; } public void addComment(DefaultIssue issue, String text, IssueChangeContext context) { issue.addComment(DefaultIssueComment.create(issue.key(), context.userUuid(), text)); issue.setUpdateDate(context.date()); issue.setChanged(true); } public void setCloseDate(DefaultIssue issue, @Nullable Date d, IssueChangeContext context) { if (relevantDateDifference(d, issue.closeDate())) { issue.setCloseDate(d); issue.setUpdateDate(context.date()); issue.setChanged(true); } } public void setCreationDate(DefaultIssue issue, Date d, IssueChangeContext context) { if (relevantDateDifference(d, issue.creationDate())) { issue.setCreationDate(d); issue.setUpdateDate(context.date()); issue.setChanged(true); } } public boolean setGap(DefaultIssue issue, @Nullable Double d, IssueChangeContext context) { if (!Objects.equals(d, issue.gap())) { issue.setGap(d); issue.setUpdateDate(context.date()); issue.setChanged(true); // Do not send notifications to prevent spam when installing the SQALE plugin, // and do not complete the changelog (for the moment) return true; } return false; } public boolean setPastGap(DefaultIssue issue, @Nullable Double previousGap, IssueChangeContext context) { Double currentGap = issue.gap(); issue.setGap(previousGap); return setGap(issue, currentGap, context); } public boolean setEffort(DefaultIssue issue, @Nullable Duration value, IssueChangeContext context) { Duration oldValue = issue.effort(); if (!Objects.equals(value, oldValue)) { issue.setEffort(value); issue.setFieldChange(context, TECHNICAL_DEBT, oldValue != null ? oldValue.toMinutes() : null, value != null ? value.toMinutes() : null); issue.setUpdateDate(context.date()); issue.setChanged(true); return true; } return false; } public boolean setPastEffort(DefaultIssue issue, @Nullable Duration previousEffort, IssueChangeContext context) { Duration currentEffort = issue.effort(); issue.setEffort(previousEffort); return setEffort(issue, currentEffort, context); } public boolean setTags(DefaultIssue issue, Collection<String> tags, IssueChangeContext context) { Set<String> newTags = RuleTagFormat.validate(tags); Set<String> oldTags = new HashSet<>(issue.tags()); if (!oldTags.equals(newTags)) { issue.setFieldChange(context, TAGS, oldTags.isEmpty() ? null : CHANGELOG_LIST_JOINER.join(oldTags), newTags.isEmpty() ? null : CHANGELOG_LIST_JOINER.join(newTags)); issue.setTags(newTags); issue.setUpdateDate(context.date()); issue.setChanged(true); issue.setSendNotifications(true); return true; } return false; } public boolean setCodeVariants(DefaultIssue issue, Set<String> currentCodeVariants, IssueChangeContext context) { Set<String> newCodeVariants = getNewCodeVariants(issue); if (!currentCodeVariants.equals(newCodeVariants)) { issue.setFieldChange(context, CODE_VARIANTS, currentCodeVariants.isEmpty() ? null : CHANGELOG_LIST_JOINER.join(currentCodeVariants), newCodeVariants.isEmpty() ? null : CHANGELOG_LIST_JOINER.join(newCodeVariants)); issue.setCodeVariants(newCodeVariants); issue.setUpdateDate(context.date()); issue.setChanged(true); issue.setSendNotifications(true); return true; } return false; } private static Set<String> getNewCodeVariants(DefaultIssue issue) { Set<String> issueCodeVariants = issue.codeVariants(); if (issueCodeVariants == null) { return Set.of(); } return issueCodeVariants.stream() .map(String::trim) .filter(s -> !s.isEmpty()) .collect(Collectors.toSet()); } public void setIssueComponent(DefaultIssue issue, String newComponentUuid, String newComponentKey, Date updateDate) { if (!Objects.equals(newComponentUuid, issue.componentUuid())) { issue.setComponentUuid(newComponentUuid); issue.setUpdateDate(updateDate); issue.setChanged(true); } // other fields (such as module, modulePath, componentKey) are read-only and set/reset for consistency only issue.setComponentKey(newComponentKey); } private static boolean relevantDateDifference(@Nullable Date left, @Nullable Date right) { return !Objects.equals(truncateMillis(left), truncateMillis(right)); } private static Date truncateMillis(@Nullable Date d) { if (d == null) { return null; } return Date.from(d.toInstant().truncatedTo(ChronoUnit.SECONDS)); } }
17,499
36.878788
168
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/IssueStorage.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.DefaultIssueComment; import org.sonar.core.issue.FieldDiffs; import org.sonar.core.util.UuidFactory; import org.sonar.db.issue.IssueChangeDto; import org.sonar.db.issue.IssueChangeMapper; public class IssueStorage { public void insertChanges(IssueChangeMapper mapper, DefaultIssue issue, UuidFactory uuidFactory) { for (DefaultIssueComment comment : issue.defaultIssueComments()) { if (comment.isNew()) { IssueChangeDto changeDto = IssueChangeDto.of(comment, issue.projectUuid()); changeDto.setUuid(uuidFactory.create()); changeDto.setProjectUuid(issue.projectUuid()); mapper.insert(changeDto); } } FieldDiffs diffs = issue.currentChange(); if (issue.isCopied()) { for (FieldDiffs d : issue.changes()) { IssueChangeDto changeDto = IssueChangeDto.of(issue.key(), d, issue.projectUuid()); changeDto.setUuid(uuidFactory.create()); changeDto.setProjectUuid(issue.projectUuid()); mapper.insert(changeDto); } } else if (!issue.isNew() && diffs != null) { IssueChangeDto changeDto = IssueChangeDto.of(issue.key(), diffs, issue.projectUuid()); changeDto.setUuid(uuidFactory.create()); changeDto.setProjectUuid(issue.projectUuid()); mapper.insert(changeDto); } } }
2,243
39.8
100
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/SearchRequest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue; import com.google.common.collect.ImmutableSet; import java.util.Collection; import java.util.List; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public class SearchRequest { private List<String> additionalFields; private Boolean asc; private Boolean assigned; private List<String> assigneesUuid; private List<String> authors; private List<String> componentUuids; private List<String> componentKeys; private String createdAfter; private String createdAt; private String createdBefore; private String createdInLast; private List<String> directories; private String facetMode; private List<String> facets; private List<String> files; private List<String> issues; private Boolean inNewCodePeriod; private Set<String> scopes; private List<String> languages; private Boolean onComponentOnly; private String branch; private String pullRequest; private int page; private int pageSize; private List<String> projectKeys; private List<String> resolutions; private Boolean resolved; private List<String> rules; private String sort; private List<String> severities; private List<String> statuses; private List<String> tags; private Set<String> types; private List<String> pciDss32; private List<String> pciDss40; private List<String> owaspTop10; private List<String> owaspAsvs40; private List<String> owaspTop10For2021; private List<String> sansTop25; private List<String> sonarsourceSecurity; private List<String> cwe; private String timeZone; private Integer owaspAsvsLevel; private List<String> codeVariants; public SearchRequest() { // nothing to do here } @CheckForNull public List<String> getAdditionalFields() { return additionalFields; } public SearchRequest setAdditionalFields(@Nullable List<String> additionalFields) { this.additionalFields = additionalFields; return this; } @CheckForNull public Boolean getAsc() { return asc; } public SearchRequest setAsc(boolean asc) { this.asc = asc; return this; } @CheckForNull public Boolean getAssigned() { return assigned; } public SearchRequest setAssigned(@Nullable Boolean assigned) { this.assigned = assigned; return this; } @CheckForNull public List<String> getAssigneeUuids() { return assigneesUuid; } public SearchRequest setAssigneesUuid(@Nullable List<String> assigneesUuid) { this.assigneesUuid = assigneesUuid; return this; } @CheckForNull public List<String> getAuthors() { return authors; } public SearchRequest setAuthors(@Nullable List<String> authors) { this.authors = authors; return this; } @CheckForNull public List<String> getComponentUuids() { return componentUuids; } public SearchRequest setComponentUuids(@Nullable List<String> componentUuids) { this.componentUuids = componentUuids; return this; } @CheckForNull public String getCreatedAfter() { return createdAfter; } public SearchRequest setCreatedAfter(@Nullable String createdAfter) { this.createdAfter = createdAfter; return this; } @CheckForNull public String getCreatedAt() { return createdAt; } public SearchRequest setCreatedAt(@Nullable String createdAt) { this.createdAt = createdAt; return this; } @CheckForNull public String getCreatedBefore() { return createdBefore; } public SearchRequest setCreatedBefore(@Nullable String createdBefore) { this.createdBefore = createdBefore; return this; } @CheckForNull public String getCreatedInLast() { return createdInLast; } public SearchRequest setCreatedInLast(@Nullable String createdInLast) { this.createdInLast = createdInLast; return this; } @CheckForNull public List<String> getDirectories() { return directories; } public SearchRequest setDirectories(@Nullable List<String> directories) { this.directories = directories; return this; } @CheckForNull public String getFacetMode() { return facetMode; } public SearchRequest setFacetMode(@Nullable String facetMode) { this.facetMode = facetMode; return this; } @CheckForNull public List<String> getFacets() { return facets; } public SearchRequest setFacets(@Nullable List<String> facets) { this.facets = facets; return this; } @CheckForNull public List<String> getFiles() { return files; } public SearchRequest setFiles(@Nullable List<String> files) { this.files = files; return this; } @CheckForNull public List<String> getIssues() { return issues; } public SearchRequest setIssues(@Nullable List<String> issues) { this.issues = issues; return this; } @CheckForNull public Set<String> getScopes() { return scopes; } public SearchRequest setScopes(@Nullable Collection<String> scopes) { this.scopes = scopes == null ? null : ImmutableSet.copyOf(scopes); return this; } @CheckForNull public List<String> getLanguages() { return languages; } public SearchRequest setLanguages(@Nullable List<String> languages) { this.languages = languages; return this; } @CheckForNull public Boolean getOnComponentOnly() { return onComponentOnly; } public SearchRequest setOnComponentOnly(@Nullable Boolean onComponentOnly) { this.onComponentOnly = onComponentOnly; return this; } public int getPage() { return page; } public SearchRequest setPage(int page) { this.page = page; return this; } public int getPageSize() { return pageSize; } public SearchRequest setPageSize(int pageSize) { this.pageSize = pageSize; return this; } @CheckForNull public List<String> getResolutions() { return resolutions; } public SearchRequest setResolutions(@Nullable List<String> resolutions) { this.resolutions = resolutions; return this; } @CheckForNull public Boolean getResolved() { return resolved; } public SearchRequest setResolved(@Nullable Boolean resolved) { this.resolved = resolved; return this; } @CheckForNull public List<String> getRules() { return rules; } public SearchRequest setRules(@Nullable List<String> rules) { this.rules = rules; return this; } @CheckForNull public String getSort() { return sort; } public SearchRequest setSort(@Nullable String sort) { this.sort = sort; return this; } @CheckForNull public List<String> getSeverities() { return severities; } public SearchRequest setSeverities(@Nullable List<String> severities) { this.severities = severities; return this; } @CheckForNull public List<String> getStatuses() { return statuses; } public SearchRequest setStatuses(@Nullable List<String> statuses) { this.statuses = statuses; return this; } @CheckForNull public List<String> getTags() { return tags; } public SearchRequest setTags(@Nullable List<String> tags) { this.tags = tags; return this; } @CheckForNull public Set<String> getTypes() { return types; } public SearchRequest setTypes(@Nullable Collection<String> types) { this.types = types == null ? null : ImmutableSet.copyOf(types); return this; } @CheckForNull public List<String> getPciDss32() { return pciDss32; } public SearchRequest setPciDss32(@Nullable List<String> pciDss32) { this.pciDss32 = pciDss32; return this; } @CheckForNull public List<String> getPciDss40() { return pciDss40; } public SearchRequest setPciDss40(@Nullable List<String> pciDss40) { this.pciDss40 = pciDss40; return this; } @CheckForNull public List<String> getOwaspAsvs40() { return owaspAsvs40; } public SearchRequest setOwaspAsvs40(@Nullable List<String> owaspAsvs40) { this.owaspAsvs40 = owaspAsvs40; return this; } @CheckForNull public List<String> getOwaspTop10() { return owaspTop10; } public SearchRequest setOwaspTop10(@Nullable List<String> owaspTop10) { this.owaspTop10 = owaspTop10; return this; } @CheckForNull public List<String> getOwaspTop10For2021() { return owaspTop10For2021; } public SearchRequest setOwaspTop10For2021(@Nullable List<String> owaspTop10For2021) { this.owaspTop10For2021 = owaspTop10For2021; return this; } @CheckForNull public List<String> getSansTop25() { return sansTop25; } public SearchRequest setSansTop25(@Nullable List<String> sansTop25) { this.sansTop25 = sansTop25; return this; } @CheckForNull public List<String> getCwe() { return cwe; } public SearchRequest setCwe(@Nullable List<String> cwe) { this.cwe = cwe; return this; } @CheckForNull public List<String> getSonarsourceSecurity() { return sonarsourceSecurity; } public SearchRequest setSonarsourceSecurity(@Nullable List<String> sonarsourceSecurity) { this.sonarsourceSecurity = sonarsourceSecurity; return this; } @CheckForNull public List<String> getComponentKeys() { return componentKeys; } public SearchRequest setComponentKeys(@Nullable List<String> componentKeys) { this.componentKeys = componentKeys; return this; } @CheckForNull public List<String> getProjectKeys() { return projectKeys; } public SearchRequest setProjectKeys(@Nullable List<String> projectKeys) { this.projectKeys = projectKeys; return this; } @CheckForNull public String getBranch() { return branch; } public SearchRequest setBranch(@Nullable String branch) { this.branch = branch; return this; } @CheckForNull public String getPullRequest() { return pullRequest; } public SearchRequest setPullRequest(@Nullable String pullRequest) { this.pullRequest = pullRequest; return this; } @CheckForNull public String getTimeZone() { return timeZone; } public SearchRequest setTimeZone(@Nullable String timeZone) { this.timeZone = timeZone; return this; } @CheckForNull public Boolean getInNewCodePeriod() { return inNewCodePeriod; } public SearchRequest setInNewCodePeriod(@Nullable Boolean inNewCodePeriod) { this.inNewCodePeriod = inNewCodePeriod; return this; } public Integer getOwaspAsvsLevel() { return owaspAsvsLevel; } public SearchRequest setOwaspAsvsLevel(@Nullable Integer owaspAsvsLevel) { this.owaspAsvsLevel = owaspAsvsLevel; return this; } @CheckForNull public List<String> getCodeVariants() { return codeVariants; } public SearchRequest setCodeVariants(@Nullable List<String> codeVariants) { this.codeVariants = codeVariants; return this; } }
11,667
21.612403
91
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/TaintChecker.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Predicate; import org.jetbrains.annotations.NotNull; import org.sonar.api.config.Configuration; import org.sonar.api.rules.RuleType; import org.sonar.core.issue.DefaultIssue; import org.sonar.db.issue.IssueDto; public class TaintChecker { protected static final String EXTRA_TAINT_REPOSITORIES = "sonar.issues.taint.extra.repositories"; private final Configuration config; private final List<String> taintRepositories; public TaintChecker(Configuration config) { this.config = config; this.taintRepositories = initializeRepositories(); } public List<IssueDto> getTaintIssuesOnly(List<IssueDto> issues) { return filterTaintIssues(issues, true); } public List<IssueDto> getStandardIssuesOnly(List<IssueDto> issues) { return filterTaintIssues(issues, false); } public Map<Boolean, List<IssueDto>> mapIssuesByTaintStatus(List<IssueDto> issues) { Map<Boolean, List<IssueDto>> issuesMap = new HashMap<>(); issuesMap.put(true, getTaintIssuesOnly(issues)); issuesMap.put(false, getStandardIssuesOnly(issues)); return issuesMap; } private List<IssueDto> filterTaintIssues(List<IssueDto> issues, boolean returnTaint) { return issues.stream() .filter(getTaintIssueFilter(returnTaint)) .toList(); } @NotNull private Predicate<IssueDto> getTaintIssueFilter(boolean returnTaint) { if (returnTaint) { return issueDto -> taintRepositories.contains(issueDto.getRuleRepo()); } return issueDto -> !taintRepositories.contains(issueDto.getRuleRepo()); } public List<String> getTaintRepositories() { return taintRepositories; } private List<String> initializeRepositories() { List<String> repositories = new ArrayList<>(List.of("roslyn.sonaranalyzer.security.cs", "javasecurity", "jssecurity", "tssecurity", "phpsecurity", "pythonsecurity")); if (!config.hasKey(EXTRA_TAINT_REPOSITORIES)) { return repositories; } repositories.addAll(Arrays.stream(config.getStringArray(EXTRA_TAINT_REPOSITORIES)).toList()); return repositories; } public boolean isTaintVulnerability(DefaultIssue issue) { return taintRepositories.contains(issue.getRuleKey().repository()) && issue.getLocations() != null && !RuleType.SECURITY_HOTSPOT.equals(issue.type()); } }
3,327
32.28
99
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.issue; import javax.annotation.ParametersAreNonnullByDefault;
962
39.125
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/index/AsyncIssueIndexing.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 interface AsyncIssueIndexing { void triggerOnIndexCreation(); void triggerForProject(String projectUuid); }
1,001
37.538462
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/index/IssueDoc.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.collect.Maps; import java.util.Collection; import java.util.Date; import java.util.Map; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.rule.Severity; import org.sonar.api.rules.RuleType; import org.sonar.api.utils.Duration; import org.sonar.server.es.BaseDoc; import org.sonar.server.permission.index.AuthorizationDoc; import org.sonar.server.security.SecurityStandards; import org.sonar.server.security.SecurityStandards.VulnerabilityProbability; import static org.sonar.server.issue.index.IssueIndexDefinition.TYPE_ISSUE; public class IssueDoc extends BaseDoc { public IssueDoc(Map<String, Object> fields) { super(TYPE_ISSUE, fields); } public IssueDoc() { super(TYPE_ISSUE, Maps.newHashMapWithExpectedSize(32)); } @Override public String getId() { return key(); } public String key() { return getField(IssueIndexDefinition.FIELD_ISSUE_KEY); } public String componentUuid() { return getField(IssueIndexDefinition.FIELD_ISSUE_COMPONENT_UUID); } public String projectUuid() { return getField(IssueIndexDefinition.FIELD_ISSUE_PROJECT_UUID); } public String branchUuid() { return getField(IssueIndexDefinition.FIELD_ISSUE_BRANCH_UUID); } public boolean isMainBranch() { return getField(IssueIndexDefinition.FIELD_ISSUE_IS_MAIN_BRANCH); } public String ruleUuid() { return getField(IssueIndexDefinition.FIELD_ISSUE_RULE_UUID); } public IssueScope scope() { return IssueScope.valueOf(getField(IssueIndexDefinition.FIELD_ISSUE_SCOPE)); } public String language() { return getField(IssueIndexDefinition.FIELD_ISSUE_LANGUAGE); } public String severity() { return getField(IssueIndexDefinition.FIELD_ISSUE_SEVERITY); } @CheckForNull public Integer line() { return getNullableField(IssueIndexDefinition.FIELD_ISSUE_LINE); } public String status() { return getField(IssueIndexDefinition.FIELD_ISSUE_STATUS); } @CheckForNull public String resolution() { return getNullableField(IssueIndexDefinition.FIELD_ISSUE_RESOLUTION); } @CheckForNull public String assigneeUuid() { return getNullableField(IssueIndexDefinition.FIELD_ISSUE_ASSIGNEE_UUID); } /** * Functional date */ public Date creationDate() { return getFieldAsDate(IssueIndexDefinition.FIELD_ISSUE_FUNC_CREATED_AT); } /** * Functional date */ public Date updateDate() { return getFieldAsDate(IssueIndexDefinition.FIELD_ISSUE_FUNC_UPDATED_AT); } @CheckForNull public Date closeDate() { return getNullableFieldAsDate(IssueIndexDefinition.FIELD_ISSUE_FUNC_CLOSED_AT); } @CheckForNull public String authorLogin() { return getNullableField(IssueIndexDefinition.FIELD_ISSUE_AUTHOR_LOGIN); } public RuleType type() { return RuleType.valueOf(getField(IssueIndexDefinition.FIELD_ISSUE_TYPE)); } @CheckForNull public Duration effort() { Number effort = getNullableField(IssueIndexDefinition.FIELD_ISSUE_EFFORT); return (effort != null) ? Duration.create(effort.longValue()) : null; } @CheckForNull public String filePath() { return getNullableField(IssueIndexDefinition.FIELD_ISSUE_FILE_PATH); } @CheckForNull public String directoryPath() { return getNullableField(IssueIndexDefinition.FIELD_ISSUE_DIRECTORY_PATH); } public IssueDoc setKey(@Nullable String s) { setField(IssueIndexDefinition.FIELD_ISSUE_KEY, s); return this; } public IssueDoc setComponentUuid(@Nullable String s) { setField(IssueIndexDefinition.FIELD_ISSUE_COMPONENT_UUID, s); return this; } public IssueDoc setProjectUuid(String s) { setField(IssueIndexDefinition.FIELD_ISSUE_PROJECT_UUID, s); setParent(AuthorizationDoc.idOf(s)); return this; } public IssueDoc setBranchUuid(String s) { setField(IssueIndexDefinition.FIELD_ISSUE_BRANCH_UUID, s); return this; } public IssueDoc setIsMainBranch(boolean b) { setField(IssueIndexDefinition.FIELD_ISSUE_IS_MAIN_BRANCH, b); return this; } public IssueDoc setRuleUuid(String s) { setField(IssueIndexDefinition.FIELD_ISSUE_RULE_UUID, s); return this; } public IssueDoc setScope(IssueScope s) { setField(IssueIndexDefinition.FIELD_ISSUE_SCOPE, s.toString()); return this; } public IssueDoc setLanguage(@Nullable String s) { setField(IssueIndexDefinition.FIELD_ISSUE_LANGUAGE, s); return this; } public IssueDoc setSeverity(@Nullable String s) { setField(IssueIndexDefinition.FIELD_ISSUE_SEVERITY, s); setField(IssueIndexDefinition.FIELD_ISSUE_SEVERITY_VALUE, Severity.ALL.indexOf(s)); return this; } public IssueDoc setLine(@Nullable Integer i) { setField(IssueIndexDefinition.FIELD_ISSUE_LINE, i); return this; } public IssueDoc setStatus(@Nullable String s) { setField(IssueIndexDefinition.FIELD_ISSUE_STATUS, s); return this; } public IssueDoc setResolution(@Nullable String s) { setField(IssueIndexDefinition.FIELD_ISSUE_RESOLUTION, s); return this; } public IssueDoc setAssigneeUuid(@Nullable String s) { setField(IssueIndexDefinition.FIELD_ISSUE_ASSIGNEE_UUID, s); return this; } public IssueDoc setFuncUpdateDate(@Nullable Date d) { setField(IssueIndexDefinition.FIELD_ISSUE_FUNC_UPDATED_AT, d); return this; } public IssueDoc setFuncCreationDate(@Nullable Date d) { setField(IssueIndexDefinition.FIELD_ISSUE_FUNC_CREATED_AT, d); return this; } public IssueDoc setFuncCloseDate(@Nullable Date d) { setField(IssueIndexDefinition.FIELD_ISSUE_FUNC_CLOSED_AT, d); return this; } public IssueDoc setAuthorLogin(@Nullable String s) { setField(IssueIndexDefinition.FIELD_ISSUE_AUTHOR_LOGIN, s); return this; } public IssueDoc setEffort(@Nullable Long l) { setField(IssueIndexDefinition.FIELD_ISSUE_EFFORT, l); return this; } public IssueDoc setFilePath(@Nullable String s) { setField(IssueIndexDefinition.FIELD_ISSUE_FILE_PATH, s); return this; } public IssueDoc setDirectoryPath(@Nullable String s) { setField(IssueIndexDefinition.FIELD_ISSUE_DIRECTORY_PATH, s); return this; } @CheckForNull public Collection<String> getTags() { return getNullableField(IssueIndexDefinition.FIELD_ISSUE_TAGS); } public IssueDoc setTags(@Nullable Collection<String> tags) { setField(IssueIndexDefinition.FIELD_ISSUE_TAGS, tags); return this; } public IssueDoc setType(RuleType type) { setField(IssueIndexDefinition.FIELD_ISSUE_TYPE, type.toString()); return this; } @CheckForNull public Collection<String> getPciDss32() { return getNullableField(IssueIndexDefinition.FIELD_ISSUE_PCI_DSS_32); } public IssueDoc setPciDss32(@Nullable Collection<String> o) { setField(IssueIndexDefinition.FIELD_ISSUE_PCI_DSS_32, o); return this; } public IssueDoc setPciDss40(@Nullable Collection<String> o) { setField(IssueIndexDefinition.FIELD_ISSUE_PCI_DSS_40, o); return this; } @CheckForNull public Collection<String> getPciDss40() { return getNullableField(IssueIndexDefinition.FIELD_ISSUE_PCI_DSS_40); } public IssueDoc setOwaspAsvs40(@Nullable Collection<String> o) { setField(IssueIndexDefinition.FIELD_ISSUE_OWASP_ASVS_40, o); return this; } @CheckForNull public Collection<String> getOwaspAsvs40() { return getNullableField(IssueIndexDefinition.FIELD_ISSUE_OWASP_ASVS_40); } @CheckForNull public Collection<String> getOwaspTop10() { return getNullableField(IssueIndexDefinition.FIELD_ISSUE_OWASP_TOP_10); } public IssueDoc setOwaspTop10(@Nullable Collection<String> o) { setField(IssueIndexDefinition.FIELD_ISSUE_OWASP_TOP_10, o); return this; } @CheckForNull public Collection<String> getOwaspTop10For2021() { return getNullableField(IssueIndexDefinition.FIELD_ISSUE_OWASP_TOP_10_2021); } public IssueDoc setOwaspTop10For2021(@Nullable Collection<String> o) { setField(IssueIndexDefinition.FIELD_ISSUE_OWASP_TOP_10_2021, o); return this; } @CheckForNull public Collection<String> getSansTop25() { return getNullableField(IssueIndexDefinition.FIELD_ISSUE_SANS_TOP_25); } public IssueDoc setSansTop25(@Nullable Collection<String> s) { setField(IssueIndexDefinition.FIELD_ISSUE_SANS_TOP_25, s); return this; } @CheckForNull public Collection<String> getCwe() { return getNullableField(IssueIndexDefinition.FIELD_ISSUE_CWE); } public IssueDoc setCwe(@Nullable Collection<String> c) { setField(IssueIndexDefinition.FIELD_ISSUE_CWE, c); return this; } @CheckForNull public SecurityStandards.SQCategory getSonarSourceSecurityCategory() { String key = getNullableField(IssueIndexDefinition.FIELD_ISSUE_SQ_SECURITY_CATEGORY); return SecurityStandards.SQCategory.fromKey(key).orElse(null); } public IssueDoc setSonarSourceSecurityCategory(@Nullable SecurityStandards.SQCategory c) { setField(IssueIndexDefinition.FIELD_ISSUE_SQ_SECURITY_CATEGORY, c == null ? null : c.getKey()); return this; } @CheckForNull public VulnerabilityProbability getVulnerabilityProbability() { Integer score = getNullableField(IssueIndexDefinition.FIELD_ISSUE_VULNERABILITY_PROBABILITY); return VulnerabilityProbability.byScore(score).orElse(null); } public IssueDoc setVulnerabilityProbability(@Nullable VulnerabilityProbability v) { setField(IssueIndexDefinition.FIELD_ISSUE_VULNERABILITY_PROBABILITY, v == null ? null : v.getScore()); return this; } public boolean isNewCodeReference() { return getField(IssueIndexDefinition.FIELD_ISSUE_NEW_CODE_REFERENCE); } public IssueDoc setIsNewCodeReference(boolean b) { setField(IssueIndexDefinition.FIELD_ISSUE_NEW_CODE_REFERENCE, b); return this; } @CheckForNull public Collection<String> getCodeVariants() { return getNullableField(IssueIndexDefinition.FIELD_ISSUE_CODE_VARIANTS); } public IssueDoc setCodeVariants(@Nullable Collection<String> codeVariants) { setField(IssueIndexDefinition.FIELD_ISSUE_CODE_VARIANTS, codeVariants); return this; } }
11,073
28.142105
106
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/index/IssueIndexDefinition.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 javax.inject.Inject; 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.newindex.NewAuthorizedIndex; import org.sonar.server.es.newindex.TypeMapping; 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 static org.sonar.server.permission.index.IndexAuthorizationConstants.TYPE_AUTHORIZATION; /** * Definition of ES index "issues", including settings and fields. */ public class IssueIndexDefinition implements IndexDefinition { public static final Index DESCRIPTOR = Index.withRelations("issues"); public static final IndexType.IndexRelationType TYPE_ISSUE = IndexType.relation(IndexType.main(DESCRIPTOR, TYPE_AUTHORIZATION), "issue"); public static final String FIELD_ISSUE_ASSIGNEE_UUID = "assignee"; public static final String FIELD_ISSUE_AUTHOR_LOGIN = "authorLogin"; public static final String FIELD_ISSUE_COMPONENT_UUID = "component"; public static final String FIELD_ISSUE_EFFORT = "effort"; public static final String FIELD_ISSUE_FILE_PATH = "filePath"; /** * Functional date */ public static final String FIELD_ISSUE_FUNC_CREATED_AT = "issueCreatedAt"; /** * Functional date */ public static final String FIELD_ISSUE_FUNC_UPDATED_AT = "issueUpdatedAt"; /** * Functional date */ public static final String FIELD_ISSUE_FUNC_CLOSED_AT = "issueClosedAt"; public static final String FIELD_ISSUE_KEY = "key"; public static final String FIELD_ISSUE_SCOPE = "scope"; public static final String FIELD_ISSUE_LANGUAGE = "language"; public static final String FIELD_ISSUE_LINE = "line"; /** * The (real) project, equivalent of projects.uuid, so * it's never empty. * This field maps the parent association with issues/authorization. */ public static final String FIELD_ISSUE_PROJECT_UUID = "project"; /** * The branch. It's never empty. It maps the DB column components.branch_uuid. * It's the UUID of the branch and it's different than {@link #FIELD_ISSUE_PROJECT_UUID}. */ public static final String FIELD_ISSUE_BRANCH_UUID = "branch"; /** * Whether component is in a main branch or not. */ public static final String FIELD_ISSUE_IS_MAIN_BRANCH = "isMainBranch"; public static final String FIELD_ISSUE_DIRECTORY_PATH = "dirPath"; public static final String FIELD_ISSUE_RESOLUTION = "resolution"; public static final String FIELD_ISSUE_RULE_UUID = "ruleUuid"; public static final String FIELD_ISSUE_SEVERITY = "severity"; public static final String FIELD_ISSUE_SEVERITY_VALUE = "severityValue"; public static final String FIELD_ISSUE_STATUS = "status"; public static final String FIELD_ISSUE_TAGS = "tags"; public static final String FIELD_ISSUE_TYPE = "type"; public static final String FIELD_ISSUE_PCI_DSS_32 = "pciDss-3.2"; public static final String FIELD_ISSUE_PCI_DSS_40 = "pciDss-4.0"; public static final String FIELD_ISSUE_OWASP_ASVS_40 = "owaspAsvs-4.0"; public static final String FIELD_ISSUE_OWASP_ASVS_40_LEVEL = "owaspAsvs-4.0-level"; public static final String FIELD_ISSUE_OWASP_TOP_10 = "owaspTop10"; public static final String FIELD_ISSUE_OWASP_TOP_10_2021 = "owaspTop10-2021"; public static final String FIELD_ISSUE_SANS_TOP_25 = "sansTop25"; public static final String FIELD_ISSUE_CWE = "cwe"; public static final String FIELD_ISSUE_SQ_SECURITY_CATEGORY = "sonarsourceSecurity"; public static final String FIELD_ISSUE_VULNERABILITY_PROBABILITY = "vulnerabilityProbability"; public static final String FIELD_ISSUE_CODE_VARIANTS = "codeVariants"; /** * Whether issue is new code for a branch using the reference branch new code definition. */ public static final String FIELD_ISSUE_NEW_CODE_REFERENCE = "isNewCodeReference"; private final Configuration config; private final boolean enableSource; @Inject public IssueIndexDefinition(Configuration config) { this(config, false); } private IssueIndexDefinition(Configuration config, boolean enableSource) { this.config = config; this.enableSource = enableSource; } /** * Keep the document sources in index so that indexer tests can verify content * of indexed documents. */ public static IssueIndexDefinition createForTest() { return new IssueIndexDefinition(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_ISSUE); mapping.keywordFieldBuilder(FIELD_ISSUE_ASSIGNEE_UUID).disableNorms().addSubFields(SORTABLE_ANALYZER).build(); mapping.keywordFieldBuilder(FIELD_ISSUE_AUTHOR_LOGIN).disableNorms().build(); mapping.keywordFieldBuilder(FIELD_ISSUE_COMPONENT_UUID).disableNorms().build(); mapping.createLongField(FIELD_ISSUE_EFFORT); mapping.keywordFieldBuilder(FIELD_ISSUE_FILE_PATH).disableNorms().addSubFields(SORTABLE_ANALYZER).build(); mapping.createDateTimeField(FIELD_ISSUE_FUNC_CREATED_AT); mapping.createDateTimeField(FIELD_ISSUE_FUNC_UPDATED_AT); mapping.createDateTimeField(FIELD_ISSUE_FUNC_CLOSED_AT); mapping.keywordFieldBuilder(FIELD_ISSUE_KEY).disableNorms().addSubFields(SORTABLE_ANALYZER).build(); mapping.keywordFieldBuilder(FIELD_ISSUE_SCOPE).disableNorms().build(); mapping.keywordFieldBuilder(FIELD_ISSUE_LANGUAGE).disableNorms().build(); mapping.createIntegerField(FIELD_ISSUE_LINE); mapping.keywordFieldBuilder(FIELD_ISSUE_PROJECT_UUID).disableNorms().addSubFields(SORTABLE_ANALYZER).build(); mapping.keywordFieldBuilder(FIELD_ISSUE_BRANCH_UUID).disableNorms().build(); mapping.createBooleanField(FIELD_ISSUE_IS_MAIN_BRANCH); mapping.keywordFieldBuilder(FIELD_ISSUE_DIRECTORY_PATH).disableNorms().build(); mapping.keywordFieldBuilder(FIELD_ISSUE_RESOLUTION).disableNorms().build(); mapping.keywordFieldBuilder(FIELD_ISSUE_RULE_UUID).disableNorms().build(); mapping.keywordFieldBuilder(FIELD_ISSUE_SEVERITY).disableNorms().build(); mapping.createByteField(FIELD_ISSUE_SEVERITY_VALUE); mapping.keywordFieldBuilder(FIELD_ISSUE_STATUS).disableNorms().addSubFields(SORTABLE_ANALYZER).build(); mapping.keywordFieldBuilder(FIELD_ISSUE_TAGS).disableNorms().build(); mapping.keywordFieldBuilder(FIELD_ISSUE_TYPE).disableNorms().build(); mapping.keywordFieldBuilder(FIELD_ISSUE_PCI_DSS_32).disableNorms().build(); mapping.keywordFieldBuilder(FIELD_ISSUE_PCI_DSS_40).disableNorms().build(); mapping.keywordFieldBuilder(FIELD_ISSUE_OWASP_ASVS_40).disableNorms().build(); mapping.keywordFieldBuilder(FIELD_ISSUE_OWASP_ASVS_40_LEVEL).disableNorms().build(); mapping.keywordFieldBuilder(FIELD_ISSUE_OWASP_TOP_10).disableNorms().build(); mapping.keywordFieldBuilder(FIELD_ISSUE_OWASP_TOP_10_2021).disableNorms().build(); mapping.keywordFieldBuilder(FIELD_ISSUE_SANS_TOP_25).disableNorms().build(); mapping.keywordFieldBuilder(FIELD_ISSUE_CWE).disableNorms().build(); mapping.keywordFieldBuilder(FIELD_ISSUE_SQ_SECURITY_CATEGORY).disableNorms().build(); mapping.keywordFieldBuilder(FIELD_ISSUE_VULNERABILITY_PROBABILITY).disableNorms().build(); mapping.createBooleanField(FIELD_ISSUE_NEW_CODE_REFERENCE); mapping.keywordFieldBuilder(FIELD_ISSUE_CODE_VARIANTS).disableNorms().build(); } }
8,741
48.389831
139
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/index/IssueIndexer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.annotations.VisibleForTesting; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.Set; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.issue.IssueDto; 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.OneToManyResilientIndexingListener; 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 java.util.Collections.emptyList; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_BRANCH_UUID; import static org.sonar.server.issue.index.IssueIndexDefinition.FIELD_ISSUE_PROJECT_UUID; import static org.sonar.server.issue.index.IssueIndexDefinition.TYPE_ISSUE; /** * Indexes issues. All issues belong directly to a project branch, so they only change when a project branch changes. */ public class IssueIndexer implements EventIndexer, AnalysisIndexer, NeedAuthorizationIndexer { /** * Indicates that es_queue.doc_id references an issue. Only this issue must be indexed. */ private static final String ID_TYPE_ISSUE_KEY = "issueKey"; /** * Indicates that es_queue.doc_id references a branch. All the issues of the branch must be indexed. * Note that the constant is misleading, but we can't update it since there might some items in the DB during the upgrade. */ private static final String ID_TYPE_BRANCH_UUID = "projectUuid"; /** * Indicates that es_queue.doc_id references a project and that all issues in it should be delete. */ private static final String ID_TYPE_DELETE_PROJECT_UUID = "deleteProjectUuid"; private static final Logger LOGGER = LoggerFactory.getLogger(IssueIndexer.class); private static final AuthorizationScope AUTHORIZATION_SCOPE = new AuthorizationScope(TYPE_ISSUE, entity -> Qualifiers.PROJECT.equals(entity.getQualifier())); private static final Set<IndexType> INDEX_TYPES = Set.of(TYPE_ISSUE); private final EsClient esClient; private final DbClient dbClient; private final IssueIteratorFactory issueIteratorFactory; private final AsyncIssueIndexing asyncIssueIndexing; public IssueIndexer(EsClient esClient, DbClient dbClient, IssueIteratorFactory issueIteratorFactory, AsyncIssueIndexing asyncIssueIndexing) { this.esClient = esClient; this.dbClient = dbClient; this.issueIteratorFactory = issueIteratorFactory; this.asyncIssueIndexing = asyncIssueIndexing; } @Override public AuthorizationScope getAuthorizationScope() { return AUTHORIZATION_SCOPE; } @Override public Set<IndexType> getIndexTypes() { return INDEX_TYPES; } @Override public Type getType() { return Type.ASYNCHRONOUS; } @Override public void triggerAsyncIndexOnStartup(Set<IndexType> uninitializedIndexTypes) { asyncIssueIndexing.triggerOnIndexCreation(); } public void indexAllIssues() { try (IssueIterator issues = issueIteratorFactory.createForAll()) { doIndex(issues, Set.of()); } } @Override public void indexOnAnalysis(String branchUuid) { try (IssueIterator issues = issueIteratorFactory.createForBranch(branchUuid)) { doIndex(issues, Set.of()); } } @Override public void indexOnAnalysis(String branchUuid, Set<String> unchangedComponentUuids) { try (IssueIterator issues = issueIteratorFactory.createForBranch(branchUuid)) { doIndex(issues, unchangedComponentUuids); } } public void indexProject(String projectUuid) { asyncIssueIndexing.triggerForProject(projectUuid); } @Override public Collection<EsQueueDto> prepareForRecoveryOnEntityEvent(DbSession dbSession, Collection<String> entityUuids, Indexers.EntityEvent cause) { return switch (cause) { case CREATION, PROJECT_KEY_UPDATE, PROJECT_TAGS_UPDATE, PERMISSION_CHANGE -> // Nothing to do, issues do not exist at project creation // Measures, permissions, project key and tags are not used in type issues/issue emptyList(); case DELETION -> { List<EsQueueDto> items = createProjectDeleteRecoveryItems(entityUuids); yield dbClient.esQueueDao().insert(dbSession, items); } }; } @Override public Collection<EsQueueDto> prepareForRecoveryOnBranchEvent(DbSession dbSession, Collection<String> branchUuids, Indexers.BranchEvent cause) { return switch (cause) { case MEASURE_CHANGE -> // Measures, permissions, project key and tags are not used in type issues/issue emptyList(); case DELETION -> { List<EsQueueDto> items = createBranchRecoveryItems(branchUuids); yield dbClient.esQueueDao().insert(dbSession, items); } }; } private static List<EsQueueDto> createProjectDeleteRecoveryItems(Collection<String> entityUuids) { return entityUuids.stream() .map(entityUuid -> createQueueDto(entityUuid, ID_TYPE_DELETE_PROJECT_UUID, entityUuid)) .toList(); } private static List<EsQueueDto> createBranchRecoveryItems(Collection<String> branchUuids) { return branchUuids.stream() .map(branchUuid -> createQueueDto(branchUuid, ID_TYPE_BRANCH_UUID, branchUuid)) .toList(); } /** * Commits the DB transaction and adds the issues to Elasticsearch index. * <p> * If indexing fails, then the recovery daemon will retry later and this * method successfully returns. Meanwhile these issues will be "eventually * consistent" when requesting the index. */ public void commitAndIndexIssues(DbSession dbSession, Collection<IssueDto> issues) { ListMultimap<String, EsQueueDto> itemsByIssueKey = ArrayListMultimap.create(); issues.stream() .map(issue -> createQueueDto(issue.getKey(), ID_TYPE_ISSUE_KEY, issue.getProjectUuid())) // a mutable ListMultimap is needed for doIndexIssueItems, so MoreCollectors.index() is // not used .forEach(i -> itemsByIssueKey.put(i.getDocId(), i)); dbClient.esQueueDao().insert(dbSession, itemsByIssueKey.values()); dbSession.commit(); doIndexIssueItems(dbSession, itemsByIssueKey); } @Override public IndexingResult index(DbSession dbSession, Collection<EsQueueDto> items) { ListMultimap<String, EsQueueDto> itemsByIssueKey = ArrayListMultimap.create(); ListMultimap<String, EsQueueDto> itemsByBranchUuid = ArrayListMultimap.create(); ListMultimap<String, EsQueueDto> itemsByDeleteProjectUuid = ArrayListMultimap.create(); items.forEach(i -> { if (ID_TYPE_ISSUE_KEY.equals(i.getDocIdType())) { itemsByIssueKey.put(i.getDocId(), i); } else if (ID_TYPE_BRANCH_UUID.equals(i.getDocIdType())) { itemsByBranchUuid.put(i.getDocId(), i); } else if (ID_TYPE_DELETE_PROJECT_UUID.equals(i.getDocIdType())) { itemsByDeleteProjectUuid.put(i.getDocId(), i); } else { LOGGER.error("Unsupported es_queue.doc_id_type for issues. Manual fix is required: " + i); } }); IndexingResult result = new IndexingResult(); result.add(doIndexIssueItems(dbSession, itemsByIssueKey)); result.add(doIndexBranchItems(dbSession, itemsByBranchUuid)); result.add(doDeleteProjectIndexItems(dbSession, itemsByDeleteProjectUuid)); return result; } private IndexingResult doIndexIssueItems(DbSession dbSession, ListMultimap<String, EsQueueDto> itemsByIssueKey) { if (itemsByIssueKey.isEmpty()) { return new IndexingResult(); } IndexingListener listener = new OneToOneResilientIndexingListener(dbClient, dbSession, itemsByIssueKey.values()); BulkIndexer bulkIndexer = createBulkIndexer(listener); bulkIndexer.start(); try (IssueIterator issues = issueIteratorFactory.createForIssueKeys(itemsByIssueKey.keySet())) { while (issues.hasNext()) { IssueDoc issue = issues.next(); bulkIndexer.add(newIndexRequest(issue)); itemsByIssueKey.removeAll(issue.getId()); } } // the remaining uuids reference issues that don't exist in db. They must // be deleted from index. itemsByIssueKey.values().forEach( item -> bulkIndexer.addDeletion(TYPE_ISSUE.getMainType(), item.getDocId(), item.getDocRouting())); return bulkIndexer.stop(); } private IndexingResult doDeleteProjectIndexItems(DbSession dbSession, ListMultimap<String, EsQueueDto> itemsByDeleteProjectUuid) { IndexingListener listener = new OneToManyResilientIndexingListener(dbClient, dbSession, itemsByDeleteProjectUuid.values()); BulkIndexer bulkIndexer = createBulkIndexer(listener); bulkIndexer.start(); for (String projectUuid : itemsByDeleteProjectUuid.keySet()) { addProjectDeletionToBulkIndexer(bulkIndexer, projectUuid); } return bulkIndexer.stop(); } private IndexingResult doIndexBranchItems(DbSession dbSession, ListMultimap<String, EsQueueDto> itemsByBranchUuid) { if (itemsByBranchUuid.isEmpty()) { return new IndexingResult(); } // one branch, referenced by es_queue.doc_id = many issues IndexingListener listener = new OneToManyResilientIndexingListener(dbClient, dbSession, itemsByBranchUuid.values()); BulkIndexer bulkIndexer = createBulkIndexer(listener); bulkIndexer.start(); for (String branchUuid : itemsByBranchUuid.keySet()) { try (IssueIterator issues = issueIteratorFactory.createForBranch(branchUuid)) { if (issues.hasNext()) { do { IssueDoc doc = issues.next(); bulkIndexer.add(newIndexRequest(doc)); } while (issues.hasNext()); } else { // branch does not exist or has no issues. In both cases, // all the documents related to this branch are deleted. Optional<BranchDto> branch = dbClient.branchDao().selectByUuid(dbSession, branchUuid); branch.ifPresent(b -> addBranchDeletionToBulkIndexer(bulkIndexer, b.getProjectUuid(), b.getUuid())); } } } return bulkIndexer.stop(); } // Used by Compute Engine, no need to recovery on errors public void deleteByKeys(String projectUuid, Collection<String> issueKeys) { if (issueKeys.isEmpty()) { return; } BulkIndexer bulkIndexer = createBulkIndexer(IndexingListener.FAIL_ON_ERROR); bulkIndexer.start(); issueKeys.forEach(issueKey -> bulkIndexer.addDeletion(TYPE_ISSUE.getMainType(), issueKey, AuthorizationDoc.idOf(projectUuid))); bulkIndexer.stop(); } @VisibleForTesting protected void index(Iterator<IssueDoc> issues) { doIndex(issues, Set.of()); } private void doIndex(Iterator<IssueDoc> issues, Set<String> unchangedComponentUuids) { BulkIndexer bulk = createBulkIndexer(IndexingListener.FAIL_ON_ERROR); bulk.start(); while (issues.hasNext()) { IssueDoc issue = issues.next(); if (shouldReindexIssue(issue, unchangedComponentUuids)) { bulk.add(newIndexRequest(issue)); } } bulk.stop(); } private static boolean shouldReindexIssue(IssueDoc issue, Set<String> unchangedComponentUuids) { return issue.getFields().get(IssueIndexDefinition.FIELD_ISSUE_COMPONENT_UUID) == null || !unchangedComponentUuids.contains(issue.componentUuid()); } private static IndexRequest newIndexRequest(IssueDoc issue) { return new IndexRequest(TYPE_ISSUE.getMainType().getIndex().getName()) .id(issue.getId()) .routing(issue.getRouting().orElseThrow(() -> new IllegalStateException("IssueDoc should define a routing"))) .source(issue.getFields()); } private static void addProjectDeletionToBulkIndexer(BulkIndexer bulkIndexer, String projectUuid) { SearchRequest search = EsClient.prepareSearch(TYPE_ISSUE.getMainType()) .routing(AuthorizationDoc.idOf(projectUuid)) .source(new SearchSourceBuilder().query(boolQuery().must(termQuery(FIELD_ISSUE_PROJECT_UUID, projectUuid)))); bulkIndexer.addDeletion(search); } private static void addBranchDeletionToBulkIndexer(BulkIndexer bulkIndexer, String projectUUid, String branchUuid) { SearchRequest search = EsClient.prepareSearch(TYPE_ISSUE.getMainType()) // routing is based on the parent (See BaseDoc#getRouting). // The parent is set to the projectUUid when an issue is indexed (See IssueDoc#setProjectUuid). We need to set it here // so that the search finds the indexed docs to be deleted. .routing(AuthorizationDoc.idOf(projectUUid)) .source(new SearchSourceBuilder().query(boolQuery().must(termQuery(FIELD_ISSUE_BRANCH_UUID, branchUuid)))); bulkIndexer.addDeletion(search); } private static EsQueueDto createQueueDto(String docId, String docIdType, String projectUuid) { return EsQueueDto.create(TYPE_ISSUE.format(), docId, docIdType, AuthorizationDoc.idOf(projectUuid)); } private BulkIndexer createBulkIndexer(IndexingListener listener) { return new BulkIndexer(esClient, TYPE_ISSUE, Size.REGULAR, listener); } }
14,835
40.325905
159
java