]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-8798 fix quality flaws
authorDaniel Schwarz <daniel.schwarz@sonarsource.com>
Tue, 8 Aug 2017 09:30:50 +0000 (11:30 +0200)
committerDaniel Schwarz <bartfastiel@users.noreply.github.com>
Wed, 9 Aug 2017 13:09:54 +0000 (15:09 +0200)
15 files changed:
server/sonar-process-monitor/src/main/java/org/sonar/application/process/AbstractProcessMonitor.java
server/sonar-process-monitor/src/main/java/org/sonar/application/process/CommandFactoryImpl.java
server/sonar-process-monitor/src/main/java/org/sonar/application/process/EsProcessMonitor.java
server/sonar-process-monitor/src/main/java/org/sonar/application/process/EsSettings.java
server/sonar-process-monitor/src/main/java/org/sonar/application/process/ProcessLauncherImpl.java
server/sonar-server/src/main/java/org/sonar/server/component/index/ComponentIndex.java
server/sonar-server/src/main/java/org/sonar/server/es/BulkIndexer.java
server/sonar-server/src/main/java/org/sonar/server/es/EsUtils.java
server/sonar-server/src/main/java/org/sonar/server/es/NewIndex.java
server/sonar-server/src/main/java/org/sonar/server/es/StickyFacetBuilder.java
server/sonar-server/src/main/java/org/sonar/server/measure/index/ProjectMeasuresIndex.java
server/sonar-server/src/main/java/org/sonar/server/rule/index/RuleIndex.java
server/sonar-server/src/main/java/org/sonar/server/test/index/TestIndex.java
server/sonar-server/src/main/java/org/sonar/server/user/index/UserIndex.java
server/sonar-server/src/test/java/org/sonar/server/issue/ws/SearchActionComponentsTest.java

index f778b6e354f752db709ea7c21cce9be77dbfaec5..1583a726a3007de7e8abe97f2d653256eee7375c 100644 (file)
@@ -30,7 +30,7 @@ import org.sonar.process.ProcessId;
 
 abstract class AbstractProcessMonitor implements ProcessMonitor {
 
-  private static final Logger LOG = LoggerFactory.getLogger(EsProcessMonitor.class);
+  private static final Logger LOG = LoggerFactory.getLogger(AbstractProcessMonitor.class);
   private static final int EXPECTED_EXIT_VALUE = 0;
 
   protected final Process process;
index fdb296347a7a119792bd1430789fd418e4e7791f..1214518fb54009ef103a1c089f817f92d3429a78 100644 (file)
@@ -85,14 +85,6 @@ public class CommandFactoryImpl implements CommandFactory {
     settingsMap.forEach((key, value) -> res.addEsOption("-E" + key + "=" + value));
 
     return res;
-
-    // FIXME quid of proxy settings and sonar.search.javaOpts/javaAdditionalOpts
-    // defaults of HTTPS are the same than HTTP defaults
-    // setSystemPropertyToDefaultIfNotSet(command, HTTPS_PROXY_HOST, HTTP_PROXY_HOST);
-    // setSystemPropertyToDefaultIfNotSet(command, HTTPS_PROXY_PORT, HTTP_PROXY_PORT);
-    // command
-    // .addJavaOptions(settings.getProps().nonNullValue(ProcessProperties.SEARCH_JAVA_OPTS))
-    // .addJavaOptions(settings.getProps().nonNullValue(ProcessProperties.SEARCH_JAVA_ADDITIONAL_OPTS));
   }
 
   private Properties buildLog4j2Properties(File logDir) {
index e7502535d54808e29f23cb1c0358484882f11a91..4572af62128359f647fdfa1769653ff9003373fa 100644 (file)
@@ -23,7 +23,6 @@ import com.google.common.net.HostAndPort;
 import io.netty.util.ThreadDeathWatcher;
 import io.netty.util.concurrent.GlobalEventExecutor;
 import java.net.InetAddress;
-import java.net.MalformedURLException;
 import java.net.UnknownHostException;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
@@ -62,7 +61,7 @@ public class EsProcessMonitor extends AbstractProcessMonitor {
   private final EsCommand esCommand;
   private AtomicReference<TransportClient> transportClient = new AtomicReference<>(null);
 
-  public EsProcessMonitor(Process process, ProcessId processId, EsCommand esCommand) throws MalformedURLException {
+  public EsProcessMonitor(Process process, ProcessId processId, EsCommand esCommand) {
     super(process, processId);
     this.esCommand = esCommand;
   }
@@ -165,7 +164,7 @@ public class EsProcessMonitor extends AbstractProcessMonitor {
   }
 
   private TransportClient buildTransportClient() {
-    org.elasticsearch.common.settings.Settings.Builder esSettings = org.elasticsearch.common.settings.Settings.builder();
+    Settings.Builder esSettings = Settings.builder();
 
     // mandatory property defined by bootstrap process
     esSettings.put("cluster.name", esCommand.getClusterName());
index cf4470e0d41bd239a1533894f58f10032ab5452d..d791a4cee530fcf9744398da805a8adfc17d0607 100644 (file)
@@ -173,7 +173,7 @@ public class EsSettings {
     }
   }
 
-  private void configureAction(Map<String, String> builder) {
+  private static void configureAction(Map<String, String> builder) {
     builder.put("action.auto_create_index", String.valueOf(false));
   }
 }
index 3ac0fd1dcd0ac75c88d8350127ca58579aec921c..b2d13441f18aca3c3dd8c0a858383a8820271212 100644 (file)
@@ -81,7 +81,9 @@ public class ProcessLauncherImpl implements ProcessLauncher {
     try {
       writeConfFiles(esCommand);
       ProcessBuilder processBuilder = create(esCommand);
-      LOG.info("Launch process[{}]: {}", processId.getKey(), String.join(" ", processBuilder.command()));
+      if (LOG.isInfoEnabled()) {
+        LOG.info("Launch process[{}]: {}", processId.getKey(), String.join(" ", processBuilder.command()));
+      }
 
       process = processBuilder.start();
 
@@ -108,7 +110,6 @@ public class ProcessLauncherImpl implements ProcessLauncher {
       IOUtils.copy(getClass().getResourceAsStream("jvm.options"), new FileOutputStream(new File(confDir, "jvm.options")));
       esCommand.getLog4j2Properties().store(new FileOutputStream(new File(confDir, "log4j2.properties")), "log42 properties file for ES bundled in SonarQube");
     } catch (IOException e) {
-      e.printStackTrace();
       throw new IllegalStateException("Failed to write ES configuration files", e);
     }
   }
@@ -121,7 +122,9 @@ public class ProcessLauncherImpl implements ProcessLauncher {
       ProcessCommands commands = allProcessesCommands.createAfterClean(processId.getIpcIndex());
 
       ProcessBuilder processBuilder = create(javaCommand);
-      LOG.info("Launch process[{}]: {}", processId.getKey(), String.join(" ", processBuilder.command()));
+      if (LOG.isInfoEnabled()) {
+        LOG.info("Launch process[{}]: {}", processId.getKey(), String.join(" ", processBuilder.command()));
+      }
       process = processBuilder.start();
       return new ProcessCommandsProcessMonitor(process, processId, commands);
     } catch (Exception e) {
@@ -143,18 +146,20 @@ public class ProcessLauncherImpl implements ProcessLauncher {
     return create(esCommand, commands);
   }
 
-  private void writeJvmOptions(EsCommand esCommand) {
+  private static void writeJvmOptions(EsCommand esCommand) {
     Path jvmOptionsFile = esCommand.getJvmOptionsFile();
     String jvmOptions = esCommand.getJvmOptions()
       .stream()
-      .map(s -> s.split(" (?=-)"))// FIXME this pattern does not allow escaping
+
+      // we do not expect the user to use parameters containing " -"
+      .map(s -> s.split(" (?=-)"))
       .flatMap(Arrays::stream)
       .collect(Collectors.joining("\n"));
     String jvmOptionsContent = ELASTICSEARCH_JVM_OPTIONS_HEADER + jvmOptions;
     try {
       Files.write(jvmOptionsFile, jvmOptionsContent.getBytes(Charset.forName("UTF-8")));
     } catch (IOException e) {
-      throw new RuntimeException("Cannot write Elasticsearch jvm options file", e);
+      throw new IllegalStateException("Cannot write Elasticsearch jvm options file", e);
     }
   }
 
@@ -199,7 +204,6 @@ public class ProcessLauncherImpl implements ProcessLauncher {
       props.putAll(javaCommand.getArguments());
       props.setProperty(PROPERTY_PROCESS_KEY, javaCommand.getProcessId().getKey());
       props.setProperty(PROPERTY_PROCESS_INDEX, Integer.toString(javaCommand.getProcessId().getIpcIndex()));
-      // FIXME is it the responsibility of child process to have this timeout (too) ?
       props.setProperty(PROPERTY_TERMINATION_TIMEOUT, "60000");
       props.setProperty(PROPERTY_SHARED_PATH, tempDir.getAbsolutePath());
       try (OutputStream out = new FileOutputStream(propertiesFile)) {
index 9078c0b2d96f7634038529e2403be75a36bbae8f..41b07f569e6b710062472db0cedfb68223b0d490 100644 (file)
@@ -32,7 +32,6 @@ import org.elasticsearch.search.SearchHit;
 import org.elasticsearch.search.SearchHits;
 import org.elasticsearch.search.aggregations.AggregationBuilders;
 import org.elasticsearch.search.aggregations.bucket.filters.FiltersAggregationBuilder;
-import org.elasticsearch.search.aggregations.bucket.filters.FiltersAggregator;
 import org.elasticsearch.search.aggregations.bucket.filters.FiltersAggregator.KeyedFilter;
 import org.elasticsearch.search.aggregations.bucket.filters.InternalFilters;
 import org.elasticsearch.search.aggregations.bucket.filters.InternalFilters.InternalBucket;
@@ -156,6 +155,6 @@ public class ComponentIndex {
     SearchHits hitList = docs.getHits();
     SearchHit[] hits = hitList.getHits();
 
-    return new ComponentHitsPerQualifier(bucket.getKey(), ComponentHit.fromSearchHits(hits), hitList.totalHits());
+    return new ComponentHitsPerQualifier(bucket.getKey(), ComponentHit.fromSearchHits(hits), hitList.getTotalHits());
   }
 }
index 8881940b02ab22d8a8f5b1a15c261b005526c843..cf931dff4963b4b1726e464934d23a4a7b429873 100644 (file)
@@ -151,8 +151,8 @@ public class BulkIndexer {
     while (true) {
       SearchHit[] hits = searchResponse.getHits().getHits();
       for (SearchHit hit : hits) {
-        SearchHitField routing = hit.field("_routing");
-        DeleteRequestBuilder deleteRequestBuilder = client.prepareDelete(hit.index(), hit.type(), hit.getId());
+        SearchHitField routing = hit.getField("_routing");
+        DeleteRequestBuilder deleteRequestBuilder = client.prepareDelete(hit.getIndex(), hit.getType(), hit.getId());
         if (routing != null) {
           deleteRequestBuilder.setRouting(routing.getValue());
         }
index 12a012d1b2d1d02b74bee400efcc6867dea9a851..d9cabf1bb59dd209133db1d8e4aaf1fd56aa8726 100644 (file)
@@ -65,7 +65,7 @@ public class EsUtils {
     return docs;
   }
 
-  public static LinkedHashMap<String, Long> termsToMap(Terms terms) {
+  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) {
@@ -115,58 +115,19 @@ public class EsUtils {
     return SPECIAL_REGEX_CHARS.matcher(str).replaceAll("\\\\$0");
   }
 
-  private static class DocScrollIterator<D extends BaseDoc> implements Iterator<D> {
-
-    private final EsClient esClient;
-    private final String scrollId;
-    private final Function<Map<String, Object>, D> docConverter;
-
-    private final Queue<SearchHit> hits = new ArrayDeque<>();
-
-    private DocScrollIterator(EsClient esClient, SearchResponse scrollResponse, Function<Map<String, Object>, D> docConverter) {
-      this.esClient = esClient;
-      this.scrollId = scrollResponse.getScrollId();
-      this.docConverter = docConverter;
-      Collections.addAll(hits, scrollResponse.getHits().getHits());
-    }
-
-    @Override
-    public boolean hasNext() {
-      if (hits.isEmpty()) {
-        SearchScrollRequestBuilder esRequest = esClient.prepareSearchScroll(scrollId)
-          .setScroll(TimeValue.timeValueMinutes(SCROLL_TIME_IN_MINUTES));
-        Collections.addAll(hits, esRequest.get().getHits().getHits());
-      }
-      return !hits.isEmpty();
-    }
-
-    @Override
-    public D next() {
-      if (!hasNext()) {
-        throw new NoSuchElementException();
-      }
-      return docConverter.apply(hits.poll().getSource());
-    }
-
-    @Override
-    public void remove() {
-      throw new UnsupportedOperationException("Cannot remove item when scrolling");
-    }
-  }
-
-  public static <ID> Iterator<ID> scrollIds(EsClient esClient, SearchResponse scrollResponse, Function<String, ID> idConverter) {
+  public static <I> Iterator<I> scrollIds(EsClient esClient, SearchResponse scrollResponse, Function<String, I> idConverter) {
     return new IdScrollIterator<>(esClient, scrollResponse, idConverter);
   }
 
-  private static class IdScrollIterator<ID> implements Iterator<ID> {
+  private static class IdScrollIterator<I> implements Iterator<I> {
 
     private final EsClient esClient;
     private final String scrollId;
-    private final Function<String, ID> idConverter;
+    private final Function<String, I> idConverter;
 
     private final Queue<SearchHit> hits = new ArrayDeque<>();
 
-    private IdScrollIterator(EsClient esClient, SearchResponse scrollResponse, Function<String, ID> idConverter) {
+    private IdScrollIterator(EsClient esClient, SearchResponse scrollResponse, Function<String, I> idConverter) {
       this.esClient = esClient;
       this.scrollId = scrollResponse.getScrollId();
       this.idConverter = idConverter;
@@ -184,7 +145,7 @@ public class EsUtils {
     }
 
     @Override
-    public ID next() {
+    public I next() {
       if (!hasNext()) {
         throw new NoSuchElementException();
       }
index 306c05752f627f31ba2bf2ed58973e7dadc866f1..bba7ef584505910f8ae2d84b9e31afe1209d27fb 100644 (file)
@@ -338,55 +338,63 @@ public class NewIndex {
     }
 
     public NewIndexType build() {
-      Map<String, Object> hash = new TreeMap<>();
       if (subFields.isEmpty()) {
-        hash.putAll(ImmutableMap.of(
-          "type", getFieldType(),
-          "index", disableSearch ? INDEX_NOT_SEARCHABLE : INDEX_SEARCHABLE,
-          "norms", valueOf(!disableNorms),
-          "store", valueOf(store)));
-        if (getFieldData()) {
-          hash.put(FIELD_FIELDDATA, FIELDDATA_ENABLED);
-        }
-      } else {
-        hash.put("type", getFieldType());
-
-        Map<String, Object> multiFields = new TreeMap<>(subFields);
-
-        if (termVectorWithPositionOffsets) {
-          multiFields.entrySet().forEach(entry -> {
-            Object subFieldMapping = entry.getValue();
-            if (subFieldMapping instanceof Map) {
-              entry.setValue(
-                addFieldToMapping(
-                  (Map<String, String>) subFieldMapping,
-                  FIELD_TERM_VECTOR, "with_positions_offsets"));
-            }
-          });
-          hash.put(FIELD_TERM_VECTOR, "with_positions_offsets");
-        }
-        if (getFieldData()) {
-          multiFields.entrySet().forEach(entry -> {
-            Object subFieldMapping = entry.getValue();
-            if (subFieldMapping instanceof Map) {
-              entry.setValue(
-                addFieldToMapping(
-                  (Map<String, String>) subFieldMapping,
-                  FIELD_FIELDDATA, FIELDDATA_ENABLED));
-            }
-          });
-          hash.put(FIELD_FIELDDATA, FIELDDATA_ENABLED);
-        }
-
-        multiFields.put(fieldName, ImmutableMap.of(
-          "type", getFieldType(),
-          "index", INDEX_SEARCHABLE,
-          "norms", "false",
-          "store", valueOf(store)));
-
-        hash.put("fields", multiFields);
+        return buildWithoutSubfields();
+      }
+      return buildWithSubfields();
+    }
+
+    private NewIndexType buildWithoutSubfields() {
+      Map<String, Object> hash = new TreeMap<>();
+      hash.putAll(ImmutableMap.of(
+        "type", getFieldType(),
+        INDEX, disableSearch ? INDEX_NOT_SEARCHABLE : INDEX_SEARCHABLE,
+        "norms", valueOf(!disableNorms),
+        "store", valueOf(store)));
+      if (getFieldData()) {
+        hash.put(FIELD_FIELDDATA, FIELDDATA_ENABLED);
+      }
+      return indexType.setProperty(fieldName, hash);
+    }
+
+    private NewIndexType buildWithSubfields() {
+      Map<String, Object> hash = new TreeMap<>();
+      hash.put("type", getFieldType());
+
+      Map<String, Object> multiFields = new TreeMap<>(subFields);
+
+      if (termVectorWithPositionOffsets) {
+        multiFields.entrySet().forEach(entry -> {
+          Object subFieldMapping = entry.getValue();
+          if (subFieldMapping instanceof Map) {
+            entry.setValue(
+              addFieldToMapping(
+                (Map<String, String>) subFieldMapping,
+                FIELD_TERM_VECTOR, "with_positions_offsets"));
+          }
+        });
+        hash.put(FIELD_TERM_VECTOR, "with_positions_offsets");
+      }
+      if (getFieldData()) {
+        multiFields.entrySet().forEach(entry -> {
+          Object subFieldMapping = entry.getValue();
+          if (subFieldMapping instanceof Map) {
+            entry.setValue(
+              addFieldToMapping(
+                (Map<String, String>) subFieldMapping,
+                FIELD_FIELDDATA, FIELDDATA_ENABLED));
+          }
+        });
+        hash.put(FIELD_FIELDDATA, FIELDDATA_ENABLED);
       }
 
+      multiFields.put(fieldName, ImmutableMap.of(
+        "type", getFieldType(),
+        INDEX, INDEX_SEARCHABLE,
+        "norms", "false",
+        "store", valueOf(store)));
+      hash.put("fields", multiFields);
+
       return indexType.setProperty(fieldName, hash);
     }
 
@@ -463,7 +471,7 @@ public class NewIndex {
     public NestedFieldBuilder addKeywordField(String fieldName) {
       return setProperty(fieldName, ImmutableMap.of(
         "type", FIELD_TYPE_KEYWORD,
-        "index", INDEX_SEARCHABLE));
+        INDEX, INDEX_SEARCHABLE));
     }
 
     public NestedFieldBuilder addDoubleField(String fieldName) {
index b714d3bbfbc089563f668e55c34685a55056b00a..d8e387f10f1a16aba0c84cbb6f56c155a247e1a1 100644 (file)
@@ -81,7 +81,8 @@ public class StickyFacetBuilder {
    * @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, Function<TermsAggregationBuilder, AggregationBuilder> additionalAggregationFilter, Object... selected) {
+  public AggregationBuilder buildStickyFacet(String fieldName, String facetName, Function<TermsAggregationBuilder, AggregationBuilder> additionalAggregationFilter,
+    Object... selected) {
     return buildStickyFacet(fieldName, facetName, FACET_DEFAULT_SIZE, additionalAggregationFilter, selected);
   }
 
index 56196237dd4820b0e2effc0a1136b44038727fd1..7d9931d074c68505b462bfbbe3314fe36478fb81 100644 (file)
@@ -284,13 +284,13 @@ public class ProjectMeasuresIndex {
     filters.put("__authorization", authorizationTypeSupport.createQueryFilter());
     Multimap<String, MetricCriterion> metricCriterionMultimap = ArrayListMultimap.create();
     query.getMetricCriteria().forEach(metricCriterion -> metricCriterionMultimap.put(metricCriterion.getMetricKey(), metricCriterion));
-    metricCriterionMultimap.asMap().entrySet().forEach(entry -> {
+    metricCriterionMultimap.asMap().forEach((key, value) -> {
       BoolQueryBuilder metricFilters = boolQuery();
-      entry.getValue()
+      value
         .stream()
         .map(ProjectMeasuresIndex::toQuery)
         .forEach(metricFilters::must);
-      filters.put(entry.getKey(), metricFilters);
+      filters.put(key, metricFilters);
     });
 
     query.getQualityGateStatus()
@@ -308,18 +308,12 @@ public class ProjectMeasuresIndex {
     query.getTags()
       .ifPresent(tags -> filters.put(FIELD_TAGS, termsQuery(FIELD_TAGS, tags)));
 
-    createTextQueryFilter(query).ifPresent(queryBuilder -> filters.put("textQuery", queryBuilder));
+    query.getQueryText()
+      .map(ProjectsTextSearchQueryFactory::createQuery)
+      .ifPresent(queryBuilder -> filters.put("textQuery", queryBuilder));
     return filters;
   }
 
-  private static Optional<QueryBuilder> createTextQueryFilter(ProjectMeasuresQuery query) {
-    Optional<String> queryText = query.getQueryText();
-    if (!queryText.isPresent()) {
-      return Optional.empty();
-    }
-    return Optional.of(ProjectsTextSearchQueryFactory.createQuery(queryText.get()));
-  }
-
   private static QueryBuilder toQuery(MetricCriterion criterion) {
     if (criterion.isNoData()) {
       return boolQuery().mustNot(
index 57f63f63196c6caa978c16cd7e7d4437874b005b..ee0a7256bea9d0368c96deadeb0ea7caafd19987 100644 (file)
@@ -215,7 +215,6 @@ public class RuleIndex {
 
   /* Build main filter (match based) */
   private static Map<String, QueryBuilder> buildFilters(RuleQuery query) {
-
     Map<String, QueryBuilder> filters = new HashMap<>();
 
     /* Add enforced filter on rules that are REMOVED */
@@ -255,14 +254,8 @@ public class RuleIndex {
     }
 
     if (isNotEmpty(query.getTags())) {
-      BoolQueryBuilder q = boolQuery();
-      query.getTags().stream()
-        .map(tag -> boolQuery()
-          .filter(QueryBuilders.termQuery(FIELD_RULE_EXTENSION_TAGS, tag))
-          .filter(termsQuery(FIELD_RULE_EXTENSION_SCOPE, RuleExtensionScope.system().getScope(), RuleExtensionScope.organization(query.getOrganization()).getScope())))
-        .map(childQuery -> JoinQueryBuilders.hasChildQuery(INDEX_TYPE_RULE_EXTENSION.getType(), childQuery, ScoreMode.None))
-        .forEach(q::should);
-      filters.put(FIELD_RULE_EXTENSION_TAGS, q);
+      filters.put(FIELD_RULE_EXTENSION_TAGS,
+        buildTagsFilter(query.getTags(), query.getOrganization()));
     }
 
     Collection<RuleType> types = query.getTypes();
@@ -301,20 +294,7 @@ public class RuleIndex {
     /* Implementation of activation query */
     QProfileDto profile = query.getQProfile();
     if (query.getActivation() != null && profile != null) {
-
-      // ActiveRule Filter (profile and inheritance)
-      BoolQueryBuilder activeRuleFilter = boolQuery();
-      addTermFilter(activeRuleFilter, FIELD_ACTIVE_RULE_PROFILE_UUID, profile.getRulesProfileUuid());
-      addTermFilter(activeRuleFilter, FIELD_ACTIVE_RULE_INHERITANCE, query.getInheritance());
-      addTermFilter(activeRuleFilter, FIELD_ACTIVE_RULE_SEVERITY, query.getActiveSeverities());
-
-      // ChildQuery
-      QueryBuilder childQuery;
-      if (activeRuleFilter.hasClauses()) {
-        childQuery = activeRuleFilter;
-      } else {
-        childQuery = matchAllQuery();
-      }
+      QueryBuilder childQuery = buildActivationFilter(query, profile);
 
       if (TRUE.equals(query.getActivation())) {
         filters.put("activation",
@@ -339,6 +319,34 @@ public class RuleIndex {
     return filters;
   }
 
+  private static BoolQueryBuilder buildTagsFilter(Collection<String> tags, OrganizationDto organization) {
+    BoolQueryBuilder q = boolQuery();
+    tags.stream()
+      .map(tag -> boolQuery()
+        .filter(QueryBuilders.termQuery(FIELD_RULE_EXTENSION_TAGS, tag))
+        .filter(termsQuery(FIELD_RULE_EXTENSION_SCOPE, RuleExtensionScope.system().getScope(), RuleExtensionScope.organization(organization).getScope())))
+      .map(childQuery -> JoinQueryBuilders.hasChildQuery(INDEX_TYPE_RULE_EXTENSION.getType(), childQuery, ScoreMode.None))
+      .forEach(q::should);
+    return q;
+  }
+
+  private static QueryBuilder buildActivationFilter(RuleQuery query, QProfileDto profile) {
+    // ActiveRule Filter (profile and inheritance)
+    BoolQueryBuilder activeRuleFilter = boolQuery();
+    addTermFilter(activeRuleFilter, FIELD_ACTIVE_RULE_PROFILE_UUID, profile.getRulesProfileUuid());
+    addTermFilter(activeRuleFilter, FIELD_ACTIVE_RULE_INHERITANCE, query.getInheritance());
+    addTermFilter(activeRuleFilter, FIELD_ACTIVE_RULE_SEVERITY, query.getActiveSeverities());
+
+    // ChildQuery
+    QueryBuilder childQuery;
+    if (activeRuleFilter.hasClauses()) {
+      childQuery = activeRuleFilter;
+    } else {
+      childQuery = matchAllQuery();
+    }
+    return childQuery;
+  }
+
   private static BoolQueryBuilder addTermFilter(BoolQueryBuilder filter, String field, @Nullable Collection<String> values) {
     if (isNotEmpty(values)) {
       BoolQueryBuilder valuesFilter = boolQuery();
index 6e57de3be2072f9c3a4c4fa5653748f446ba4718..90dd3cc000d4b2a9cb08f0599bd6879834976b85 100644 (file)
@@ -53,7 +53,7 @@ public class TestIndex {
       .setSize(1)
       .setQuery(boolQuery().must(matchAllQuery()).filter(termQuery(FIELD_TEST_UUID, testUuid)))
       .get().getHits().getHits()) {
-      coveredFiles.addAll(new TestDoc(hit.sourceAsMap()).coveredFiles());
+      coveredFiles.addAll(new TestDoc(hit.getSourceAsMap()).coveredFiles());
     }
 
     return coveredFiles;
@@ -97,7 +97,7 @@ public class TestIndex {
       .setQuery(boolQuery().must(matchAllQuery()).filter(termQuery(FIELD_TEST_UUID, testUuid)))
       .get().getHits().getHits();
     if (hits.length > 0) {
-      return Optional.of(new TestDoc(hits[0].sourceAsMap()));
+      return Optional.of(new TestDoc(hits[0].getSourceAsMap()));
     }
     return Optional.absent();
   }
index 8eb0f0213e8f0f437572e0a8ab6380fee130d08b..0ddb194e46d39cd6f89d82b9bfd3a01fdccff17e 100644 (file)
@@ -90,7 +90,7 @@ public class UserIndex {
             .should(matchQuery(SORTABLE_ANALYZER.subField(FIELD_SCM_ACCOUNTS), scmAccount))))
         .setSize(3);
       for (SearchHit hit : request.get().getHits().getHits()) {
-        result.add(new UserDoc(hit.sourceAsMap()));
+        result.add(new UserDoc(hit.getSourceAsMap()));
       }
     }
     return result;
index 41e70c4732274ac6f3d4ecbc705c7bcdf7d3a99b..29fac927c51edcf0b177351670b4e43ab5988f87 100644 (file)
@@ -23,7 +23,6 @@ import java.io.IOException;
 import java.util.List;
 import org.junit.After;
 import org.junit.Before;
-import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.Test;
 import org.sonar.api.config.internal.MapSettings;
@@ -210,7 +209,6 @@ public class SearchActionComponentsTest {
       .assertJson(this.getClass(), "no_issue.json");
   }
 
-  @Ignore
   @Test
   public void search_since_leak_period_on_project() throws Exception {
     ComponentDto project = insertComponent(ComponentTesting.newPublicProjectDto(otherOrganization2, "P1").setDbKey("PK1"));
@@ -239,7 +237,6 @@ public class SearchActionComponentsTest {
       .assertJson(this.getClass(), "search_since_leak_period.json");
   }
 
-  @Ignore
   @Test
   public void search_since_leak_period_on_file_in_module_project() throws Exception {
     ComponentDto project = insertComponent(ComponentTesting.newPublicProjectDto(defaultOrganization, "P1").setDbKey("PK1"));