]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-5007 introduce org.sonar.server.search.BaseDoc
authorSimon Brandhof <simon.brandhof@sonarsource.com>
Mon, 19 May 2014 16:55:29 +0000 (18:55 +0200)
committerSimon Brandhof <simon.brandhof@sonarsource.com>
Mon, 19 May 2014 19:07:03 +0000 (21:07 +0200)
15 files changed:
sonar-server/src/main/java/org/sonar/server/qualityprofile/index/ActiveRuleDoc.java
sonar-server/src/main/java/org/sonar/server/qualityprofile/index/ActiveRuleIndex.java
sonar-server/src/main/java/org/sonar/server/qualityprofile/index/ActiveRuleNormalizer.java
sonar-server/src/main/java/org/sonar/server/qualityprofile/index/ActiveRuleQuery.java [deleted file]
sonar-server/src/main/java/org/sonar/server/rule2/index/RuleDoc.java
sonar-server/src/main/java/org/sonar/server/rule2/index/RuleIndex.java
sonar-server/src/main/java/org/sonar/server/rule2/ws/SearchAction.java
sonar-server/src/main/java/org/sonar/server/search/BaseDoc.java [new file with mode: 0644]
sonar-server/src/main/java/org/sonar/server/search/BaseIndex.java
sonar-server/src/main/java/org/sonar/server/search/QueryOptions.java
sonar-server/src/main/java/org/sonar/server/search/SourceFields.java [new file with mode: 0644]
sonar-server/src/test/java/org/sonar/server/rule2/index/RuleIndexMediumTest.java
sonar-server/src/test/java/org/sonar/server/rule2/ws/RulesWebServiceTest.java
sonar-server/src/test/java/org/sonar/server/search/BaseDocTest.java [new file with mode: 0644]
sonar-server/src/test/java/org/sonar/server/ws/WsTester.java

index a2f6e8329f666da09c7fb7a4b6ed01a02937bd64..2e7962b684addc1f834685398df6418c7089ccca 100644 (file)
  */
 package org.sonar.server.qualityprofile.index;
 
+import com.google.common.base.Preconditions;
 import org.sonar.core.qualityprofile.db.ActiveRuleKey;
 import org.sonar.server.qualityprofile.ActiveRule;
+import org.sonar.server.search.BaseDoc;
 
 import javax.annotation.CheckForNull;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
-public class ActiveRuleDoc implements ActiveRule {
+public class ActiveRuleDoc extends BaseDoc implements ActiveRule {
 
-  private final Map<String, Object> fields;
   private final ActiveRuleKey key;
 
   public ActiveRuleDoc(Map<String, Object> fields) {
-    ActiveRuleKey key = ActiveRuleKey.parse((String)fields.get(ActiveRuleNormalizer.ActiveRuleField.KEY.key()));
-    if(key == null){
-      throw new IllegalStateException("Invalid ActiveRuleKey!");
-    }
-    this.fields = fields;
-    this.key = key;
+    super(fields);
+    this.key = ActiveRuleKey.parse((String) get(ActiveRuleNormalizer.ActiveRuleField.KEY.key()));
+    Preconditions.checkArgument(key!=null, "Invalid ActiveRuleKey!");
   }
 
   @Override
@@ -48,29 +46,29 @@ public class ActiveRuleDoc implements ActiveRule {
 
   @Override
   public String severity() {
-    return (String) this.fields.get(ActiveRuleNormalizer.ActiveRuleField.SEVERITY.key());
+    return (String) get(ActiveRuleNormalizer.ActiveRuleField.SEVERITY.key());
   }
 
   @Override
   public ActiveRule.Inheritance inheritance() {
-    String inheritance = (String) this.fields.get(ActiveRuleNormalizer.ActiveRuleField.INHERITANCE.key());
-    if(inheritance == null || inheritance.isEmpty() ||
-      inheritance.toLowerCase().contains("none")){
+    String inheritance = get(ActiveRuleNormalizer.ActiveRuleField.INHERITANCE.key());
+    if (inheritance == null || inheritance.isEmpty() ||
+      inheritance.toLowerCase().contains("none")) {
       return Inheritance.NONE;
-    } else if(inheritance.toLowerCase().contains("herit")) {
+    } else if (inheritance.toLowerCase().contains("herit")) {
       return Inheritance.INHERIT;
-    } else if(inheritance.toLowerCase().contains("over")) {
+    } else if (inheritance.toLowerCase().contains("over")) {
       return Inheritance.OVERRIDE;
     } else {
-      throw new IllegalStateException("Value \"" +inheritance+"\" is not valid for rule's inheritance");
+      throw new IllegalStateException("Value \"" + inheritance + "\" is not valid for rule's inheritance");
     }
   }
 
   @Override
   @CheckForNull
   public ActiveRuleKey parentKey() {
-    String data = (String) this.fields.get(ActiveRuleNormalizer.ActiveRuleField.PARENT_KEY.key());
-    if(data != null && !data.isEmpty()){
+    String data = get(ActiveRuleNormalizer.ActiveRuleField.PARENT_KEY.key());
+    if (data != null && !data.isEmpty()) {
       return ActiveRuleKey.parse(data);
     }
     return null;
@@ -79,8 +77,8 @@ public class ActiveRuleDoc implements ActiveRule {
   @Override
   public Map<String, String> params() {
     Map<String, String> params = new HashMap<String, String>();
-    if (this.fields.containsKey(ActiveRuleNormalizer.ActiveRuleField.PARAMS.key())) {
-      List<Map<String, String>> allParams = (List<Map<String, String>>) this.fields.get(ActiveRuleNormalizer.ActiveRuleField.PARAMS.key());
+    List<Map<String, String>> allParams = get(ActiveRuleNormalizer.ActiveRuleField.PARAMS.key());
+    if (allParams != null) {
       for (Map<String, String> param : allParams) {
         params.put(param.get(ActiveRuleNormalizer.ActiveRuleParamField.NAME.key()),
           param.get(ActiveRuleNormalizer.ActiveRuleParamField.VALUE.key()));
index b0296d502264a369145039c941734f2dc3076687..91fd57ee49d0effc63cc8e802b8bf90f72c795ff 100644 (file)
@@ -53,10 +53,12 @@ import org.sonar.server.es.ESNode;
 import org.sonar.server.qualityprofile.ActiveRule;
 import org.sonar.server.rule2.index.RuleIndexDefinition;
 import org.sonar.server.search.BaseIndex;
+import org.sonar.server.search.QueryOptions;
 
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Map;
 
 import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
 
@@ -119,15 +121,14 @@ public class ActiveRuleIndex extends BaseIndex<ActiveRule, ActiveRuleDto, Active
   }
 
   @Override
-  public ActiveRule toDoc(GetResponse response) {
-    return new ActiveRuleDoc(response.getSource());
+  public ActiveRule toDoc(Map<String,Object> fields, QueryOptions options) {
+    return new ActiveRuleDoc(fields);
   }
 
   /**
    * finder methods
    */
   public List<ActiveRule> findByRule(RuleKey key) {
-
     SearchRequestBuilder request = getClient().prepareSearch(this.getIndexName())
       .setQuery(QueryBuilders
         .hasParentQuery(this.getParentType(),
@@ -140,7 +141,7 @@ public class ActiveRuleIndex extends BaseIndex<ActiveRule, ActiveRuleDto, Active
 
     List<ActiveRule> activeRules = new ArrayList<ActiveRule>();
     for (SearchHit hit : response.getHits()) {
-      activeRules.add(new ActiveRuleDoc(hit.getSource()));
+      activeRules.add(toDoc(hit.getSource(), QueryOptions.DEFAULT));
     }
 
     return activeRules;
@@ -156,6 +157,6 @@ public class ActiveRuleIndex extends BaseIndex<ActiveRule, ActiveRuleDto, Active
       .setType(this.getIndexType())
       .setIndex(this.getIndexName())
       .setId(ActiveRuleKey.of(qualityProfileKey, ruleKey).toString())
-      .get());
+      .get().getSource(), QueryOptions.DEFAULT);
   }
 }
index 1fc29a110d83c80dba95014aa02be47612c7ea92..f60b7372a28d910338cf4b4aedc2bb8483b3dde5 100644 (file)
@@ -19,6 +19,7 @@
  */
 package org.sonar.server.qualityprofile.index;
 
+import com.google.common.base.Preconditions;
 import org.elasticsearch.action.update.UpdateRequest;
 import org.sonar.core.persistence.DbSession;
 import org.sonar.core.qualityprofile.db.ActiveRuleDto;
@@ -93,10 +94,7 @@ public class ActiveRuleNormalizer extends BaseNormalizer<ActiveRuleDto, ActiveRu
   }
 
   public UpdateRequest normalize(ActiveRuleParamDto param, ActiveRuleKey key) {
-
-    if (key == null) {
-      throw new IllegalStateException("Cannot normalize ActiveRuleParamDto for null key of ActiveRule");
-    }
+    Preconditions.checkArgument(key != null, "Cannot normalize ActiveRuleParamDto for null key of ActiveRule");
 
     Map<String, Object> newParam = new HashMap<String, Object>();
     newParam.put("_id", param.getKey());
@@ -108,37 +106,39 @@ public class ActiveRuleNormalizer extends BaseNormalizer<ActiveRuleDto, ActiveRu
   }
 
   @Override
-  public UpdateRequest normalize(ActiveRuleDto rule) {
-
-    ActiveRuleKey key = rule.getKey();
-    if (key == null) {
-      throw new IllegalStateException("Cannot normalize ActiveRuleDto with null key");
-    }
+  public UpdateRequest normalize(ActiveRuleDto activeRuleDto) {
+    ActiveRuleKey key = activeRuleDto.getKey();
+    Preconditions.checkArgument(key != null, "Cannot normalize ActiveRuleDto with null key");
 
     Map<String, Object> newRule = new HashMap<String, Object>();
     newRule.put("_parent", key.ruleKey().toString());
     newRule.put("ruleKey", key.ruleKey().toString());
     newRule.put(ActiveRuleField.KEY.key(), key.toString());
-    newRule.put(ActiveRuleField.INHERITANCE.key(), rule.getInheritance());
-    newRule.put(ActiveRuleField.PROFILE_ID.key(), rule.getProfileId());
-    newRule.put(ActiveRuleField.SEVERITY.key(), rule.getSeverityString());
+    newRule.put(ActiveRuleField.INHERITANCE.key(), activeRuleDto.getInheritance());
+    newRule.put(ActiveRuleField.PROFILE_ID.key(), activeRuleDto.getProfileId());
+    newRule.put(ActiveRuleField.SEVERITY.key(), activeRuleDto.getSeverityString());
 
     //TODO this should be generated by RegisterRule and modified in DTO.
-    if (rule.getParentId() != null) {
+    String parentKey = null;
+    if (activeRuleDto.getParentId() != null) {
       DbSession session = db.openSession(false);
-      ActiveRuleDto dto = this.db.activeRuleDao().getById(rule.getParentId(), session);
-      session.close();
-      newRule.put(ActiveRuleField.PARENT_KEY.key(), dto.getKey().toString());
+      try {
+        ActiveRuleDto parentDto = db.activeRuleDao().getById(activeRuleDto.getParentId(), session);
+        parentKey = parentDto.getKey().toString();
+      } finally {
+        session.close();
+      }
     }
+    newRule.put(ActiveRuleField.PARENT_KEY.key(), parentKey);
 
     Map<String, Object> upsert = new HashMap<String, Object>(newRule);
     upsert.put(ActiveRuleField.PARAMS.key(), new ArrayList());
 
     /* Creating updateRequest */
-   return new UpdateRequest()
+    return new UpdateRequest()
       .routing(key.ruleKey().toString())
-      .id(rule.getKey().toString())
-      .parent(rule.getKey().ruleKey().toString())
+      .id(activeRuleDto.getKey().toString())
+      .parent(activeRuleDto.getKey().ruleKey().toString())
       .doc(newRule)
       .upsert(upsert);
   }
diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/index/ActiveRuleQuery.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/index/ActiveRuleQuery.java
deleted file mode 100644 (file)
index 81974f2..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with 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.qualityprofile.index;
-
-public class ActiveRuleQuery {
-}
index dc316d10a884225a3a86e2593abe797eba6f8e91..619e134e50b8c3c4a65190a579e8a399483fc851 100644 (file)
@@ -27,6 +27,7 @@ import org.sonar.api.server.rule.RuleParamType;
 import org.sonar.server.rule2.Rule;
 import org.sonar.server.rule2.RuleParam;
 import org.sonar.server.rule2.index.RuleNormalizer.RuleField;
+import org.sonar.server.search.BaseDoc;
 import org.sonar.server.search.IndexUtils;
 
 import javax.annotation.CheckForNull;
@@ -38,17 +39,15 @@ import java.util.Map;
 /**
  * Implementation of Rule based on an Elasticsearch document
  */
-class RuleDoc implements Rule {
-
-  private final Map<String, Object> fields;
+class RuleDoc extends BaseDoc implements Rule {
 
   public RuleDoc(Map<String, Object> fields) {
-    this.fields = fields;
+    super(fields);
   }
 
   @Override
   public RuleKey key() {
-    String key = (String) fields.get(RuleField.KEY.key());
+    String key = get(RuleField.KEY.key());
     if (key == null || key.isEmpty()) {
       throw new IllegalStateException("Missing values for RuleKey in RuleDoc");
     } else {
@@ -59,68 +58,68 @@ class RuleDoc implements Rule {
   @Override
   @CheckForNull
   public String internalKey() {
-    return (String) fields.get(RuleField.INTERNAL_KEY.key());
+    return get(RuleField.INTERNAL_KEY.key());
   }
 
   @Override
   public String markdownNote() {
-    return (String) fields.get(RuleField.NOTE.key());
+    return get(RuleField.NOTE.key());
   }
 
   @Override
   @CheckForNull
   public String language() {
-    return (String) fields.get(RuleField.LANGUAGE.key());
+    return get(RuleField.LANGUAGE.key());
   }
 
   @Override
   @CheckForNull
   public String name() {
-    return (String) fields.get(RuleField.NAME.key());
+    return get(RuleField.NAME.key());
   }
 
   @Override
   @CheckForNull
   public String htmlDescription() {
-    return (String) fields.get(RuleField.HTML_DESCRIPTION.key());
+    return get(RuleField.HTML_DESCRIPTION.key());
   }
 
   @Override
   @CheckForNull
   public String severity() {
-    return (String) fields.get(RuleField.SEVERITY.key());
+    return (String) get(RuleField.SEVERITY.key());
   }
 
   @Override
   @CheckForNull
   public RuleStatus status() {
-    return RuleStatus.valueOf((String) fields.get(RuleField.STATUS.key()));
+    return RuleStatus.valueOf((String) get(RuleField.STATUS.key()));
   }
 
   @Override
   @CheckForNull
   public boolean template() {
-    return (Boolean) fields.get(RuleField.TEMPLATE.key());
+    return (Boolean) get(RuleField.TEMPLATE.key());
   }
 
   @Override
   @CheckForNull
   public List<String> tags() {
-    return (List<String>) fields.get(RuleField.TAGS.key());
+    return (List<String>) get(RuleField.TAGS.key());
   }
 
   @Override
   @CheckForNull
   public List<String> systemTags() {
-    return (List<String>) fields.get(RuleField.SYSTEM_TAGS.key());
+    return (List<String>) get(RuleField.SYSTEM_TAGS.key());
   }
 
   @Override
   @CheckForNull
   public List<RuleParam> params() {
     List<RuleParam> params = new ArrayList<RuleParam>();
-    if (this.fields.get(RuleField.PARAMS.key()) != null) {
-      List<Map<String, Object>> esParams = (List<Map<String, Object>>) this.fields.get(RuleField.PARAMS.key());
+    if (this.get(RuleField.PARAMS.key()) != null) {
+      List<Map<String, Object>> esParams = this.get(RuleField.PARAMS.key());
       for (final Map<String, Object> param : esParams) {
         params.add(new RuleParam() {
           {
@@ -165,13 +164,13 @@ class RuleDoc implements Rule {
   @Override
   @CheckForNull
   public String debtSubCharacteristicKey(){
-    return (String) fields.get(RuleField.SUB_CHARACTERISTIC.key());
+    return (String) get(RuleField.SUB_CHARACTERISTIC.key());
   }
 
   @Override
   @CheckForNull
   public DebtRemediationFunction debtRemediationFunction() {
-    final String function = (String) this.fields.get(RuleField.DEBT_FUNCTION_TYPE.key());
+    final String function = this.get(RuleField.DEBT_FUNCTION_TYPE.key());
     if(function == null || function.isEmpty()){
       return null;
     } else {
@@ -183,12 +182,12 @@ class RuleDoc implements Rule {
 
         @Override
         public String coefficient() {
-          return (String) fields.get(RuleField.DEBT_FUNCTION_COEFFICIENT.key());
+          return (String) get(RuleField.DEBT_FUNCTION_COEFFICIENT.key());
         }
 
         @Override
         public String offset() {
-          return (String) fields.get(RuleField.DEBT_FUNCTION_OFFSET.key());
+          return (String) get(RuleField.DEBT_FUNCTION_OFFSET.key());
         }
       };
     }
@@ -197,29 +196,29 @@ class RuleDoc implements Rule {
   @Override
   @CheckForNull
   public String noteLogin() {
-    return (String) fields.get(RuleField.NOTE_LOGIN.key());
+    return (String) get(RuleField.NOTE_LOGIN.key());
   }
 
   @Override
   public Date noteCreatedAt() {
-    return IndexUtils.parseDateTime((String) fields.get(RuleField.NOTE_CREATED_AT.key()));
+    return IndexUtils.parseDateTime((String) get(RuleField.NOTE_CREATED_AT.key()));
   }
 
   @Override
   public Date noteUpdatedAt() {
-    return IndexUtils.parseDateTime((String) fields.get(RuleField.NOTE_UPDATED_AT.key()));
+    return IndexUtils.parseDateTime((String) get(RuleField.NOTE_UPDATED_AT.key()));
   }
 
   @Override
   @CheckForNull
   public Date createdAt() {
-    return IndexUtils.parseDateTime((String) fields.get(RuleField.CREATED_AT.key()));
+    return IndexUtils.parseDateTime((String)get(RuleField.CREATED_AT.key()));
   }
 
   @Override
   @CheckForNull
   public Date updatedAt() {
-    return IndexUtils.parseDateTime((String) fields.get(RuleField.UPDATED_AT.key()));
+    return IndexUtils.parseDateTime((String) get(RuleField.UPDATED_AT.key()));
   }
 
   @Override
index 61ab11ef7161e1fd26c51e27062f48e4a7291ec8..d8bfee420635e0af25bb4f6d5117d5a82a1b399f 100644 (file)
@@ -48,6 +48,7 @@ import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.HashSet;
+import java.util.Map;
 import java.util.Set;
 
 import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
@@ -338,9 +339,9 @@ public class RuleIndex extends BaseIndex<Rule, RuleDto, RuleKey> {
 
 
   @Override
-  protected Rule toDoc(GetResponse response) {
-    Preconditions.checkArgument(response != null, "Cannot construct Rule with null response!!!");
-    return new RuleDoc(response.getSource());
+  protected Rule toDoc(Map<String,Object> fields, QueryOptions options) {
+    Preconditions.checkArgument(fields != null, "Cannot construct Rule with null response!!!");
+    return new RuleDoc(fields);
   }
 
   public Set<String> terms(String... fields) {
index 92644eff91593a32f7626996bcf121f8a9c082d2..d1223ca35ce5985ef505d83b4ec8f39a9dc8e92a 100644 (file)
@@ -219,9 +219,7 @@ public class SearchAction implements RequestHandler {
     json.prop(PARAM_PAGE_SIZE, request.mandatoryParamAsInt(PARAM_PAGE_SIZE));
   }
 
-
   private void writeRules(RuleResult result, JsonWriter json) {
-
     json.name("rules").beginArray();
     for (Rule rule : result.getHits()) {
 
@@ -270,9 +268,10 @@ public class SearchAction implements RequestHandler {
           .prop("key",activeRule.key())
           .prop("inherit", activeRule.inheritance())
           .prop("severity", activeRule.severity());
-        if(activeRule.parentKey() != null){
-          json.prop("parent",activeRule.parentKey());
-        }
+        // TODO
+//        if(activeRule.parentKey() != null){
+//          json.prop("parent",activeRule.parentKey());
+//        }
 
         json
           .name("params").beginArray();
diff --git a/sonar-server/src/main/java/org/sonar/server/search/BaseDoc.java b/sonar-server/src/main/java/org/sonar/server/search/BaseDoc.java
new file mode 100644 (file)
index 0000000..383b2e6
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with 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.search;
+
+import javax.annotation.CheckForNull;
+import java.util.Map;
+
+/**
+ * Base implementation for business objects based on elasticsearch document
+ */
+public abstract class BaseDoc {
+
+  private final Map<String,Object> fields;
+
+  protected BaseDoc(Map<String,Object> fields) {
+    this.fields = fields;
+  }
+
+  @CheckForNull
+  protected <K> K get(String key) {
+    if (!fields.containsKey(key)) {
+      throw new IllegalStateException(String.format("Field %s not specified in query options", key));
+    }
+    return (K)fields.get(key);
+  }
+}
index 0d4141da0579a86cfcfc55a0cee4c18fe3deb349..ea3abff31509da4e542820e2773193aca572d505 100644 (file)
@@ -41,6 +41,7 @@ import java.io.IOException;
 import java.io.Serializable;
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.Map;
 import java.util.concurrent.ExecutionException;
 
 public abstract class BaseIndex<D, E extends Dto<K>, K extends Serializable>
@@ -146,7 +147,7 @@ public abstract class BaseIndex<D, E extends Dto<K>, K extends Serializable>
 
   /* Base CRUD methods */
 
-  protected abstract D toDoc(GetResponse response);
+  protected abstract D toDoc(Map<String,Object> fields, QueryOptions options);
 
   public D getByKey(K key) {
     GetResponse response = getClient().prepareGet()
@@ -156,7 +157,7 @@ public abstract class BaseIndex<D, E extends Dto<K>, K extends Serializable>
       .setRouting(this.getKeyValue(key))
       .get();
     if (response.isExists()) {
-      return toDoc(response);
+      return toDoc(response.getSource(), QueryOptions.DEFAULT);
     }
     return null;
   }
index 1604aa13ed4790bc5f3c31baf895fcd63e76123c..1f2c6cd8b60649f8a5d9c8ba568152687e84552f 100644 (file)
@@ -36,6 +36,8 @@ import java.util.Set;
  */
 public class QueryOptions {
 
+  public static final QueryOptions DEFAULT = new QueryOptions();
+
   public static final int DEFAULT_OFFSET = 0;
   public static final int DEFAULT_LIMIT = 10;
   public static final boolean DEFAULT_FACET = true;
diff --git a/sonar-server/src/main/java/org/sonar/server/search/SourceFields.java b/sonar-server/src/main/java/org/sonar/server/search/SourceFields.java
new file mode 100644 (file)
index 0000000..2afdaec
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with 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.search;
+
+import java.util.Map;
+
+public class SourceFields {
+
+  public static String get(String key, Map<String,Object> source, QueryOptions options) {
+    return null;
+  }
+}
index 21876400ca3598647ae0ab8fd11e9ee17d76193d..cd963a28e73deac10db043930dc31b9917bf5d60 100644 (file)
@@ -43,6 +43,7 @@ import java.util.Arrays;
 import java.util.Collections;
 
 import static org.fest.assertions.Assertions.assertThat;
+import static org.fest.assertions.Fail.fail;
 
 public class RuleIndexMediumTest {
 
@@ -149,7 +150,13 @@ public class RuleIndexMediumTest {
     Rule hit = Iterables.getFirst(results.getHits(), null);
     assertThat(hit.language()).isEqualTo("js");
     assertThat(hit.status()).isEqualTo(RuleStatus.READY);
-    assertThat(hit.htmlDescription()).isNull();
+
+    try {
+      hit.htmlDescription();
+      fail();
+    } catch (IllegalStateException e) {
+      assertThat(e).hasMessage("Field htmlDesc not specified in query options");
+    }
   }
 
   @Test
index fbbd74652f5746d0ca58e32b8eac3ded23b0a7cd..65d0650d34701c0b716735e217ed3688b3f5ebc5 100644 (file)
  */
 package org.sonar.server.rule2.ws;
 
-import com.google.common.base.Charsets;
 import com.google.common.collect.ImmutableSet;
-import com.google.common.io.Resources;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.ClassRule;
 import org.junit.Test;
-import org.skyscreamer.jsonassert.JSONAssert;
 import org.sonar.api.rule.RuleKey;
 import org.sonar.api.rule.RuleStatus;
 import org.sonar.api.rule.Severity;
@@ -72,7 +69,7 @@ public class RulesWebServiceTest {
   }
 
   @After
-  public void after(){
+  public void after() {
     session.close();
   }
 
@@ -117,10 +114,7 @@ public class RulesWebServiceTest {
     WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "search");
     WsTester.Result result = request.execute();
 
-    String json = result.outputAsString();
-    String expectedJson = Resources.toString(getClass().getResource("RulesWebServiceTest/search_2_rules.json"), Charsets.UTF_8);
-
-    JSONAssert.assertEquals(expectedJson, json, false);
+    result.assertJson(getClass(), "search_2_rules.json", false);
   }
 
 
@@ -139,7 +133,7 @@ public class RulesWebServiceTest {
     WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "search");
     WsTester.Result result = request.execute();
 
-    result.assertJson(this.getClass(),"search_debt_rule.json");
+    result.assertJson(this.getClass(), "search_debt_rule.json");
   }
 
 
@@ -149,7 +143,7 @@ public class RulesWebServiceTest {
     tester.get(QualityProfileDao.class).insert(profile, session);
 
     RuleDto rule = newRuleDto(RuleKey.of(profile.getLanguage(), "S001"));
-    ruleDao.insert(rule,  session);
+    ruleDao.insert(rule, session);
 
     ActiveRuleDto activeRule = newActiveRule(profile, rule);
     tester.get(ActiveRuleDao.class).insert(activeRule, session);
@@ -161,11 +155,11 @@ public class RulesWebServiceTest {
 
     MockUserSession.set();
     WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "search");
-    request.setParam("q","S001");
-    request.setParam("activation","all");
+    request.setParam("q", "S001");
+    request.setParam("activation", "all");
     WsTester.Result result = request.execute();
 
-    result.assertJson(this.getClass(),"search_active_rules.json");
+    result.assertJson(this.getClass(), "search_active_rules.json");
   }
 
   @Test
@@ -174,7 +168,7 @@ public class RulesWebServiceTest {
     tester.get(QualityProfileDao.class).insert(profile, session);
 
     RuleDto rule = newRuleDto(RuleKey.of(profile.getLanguage(), "S001"));
-    ruleDao.insert(rule,  session);
+    ruleDao.insert(rule, session);
 
     ActiveRuleDto activeRule = newActiveRule(profile, rule);
     tester.get(ActiveRuleDao.class).insert(activeRule, session);
@@ -186,11 +180,11 @@ public class RulesWebServiceTest {
 
     MockUserSession.set();
     WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "search");
-    request.setParam("q","S001");
-    request.setParam("activation","false");
+    request.setParam("q", "S001");
+    request.setParam("activation", "false");
     WsTester.Result result = request.execute();
 
-    result.assertJson(this.getClass(),"search_no_active_rules.json");
+    result.assertJson(this.getClass(), "search_no_active_rules.json");
   }
 
   @Test
@@ -204,7 +198,7 @@ public class RulesWebServiceTest {
     session.commit();
 
     RuleDto rule = newRuleDto(RuleKey.of(profile.getLanguage(), "S001"));
-    ruleDao.insert(rule,  session);
+    ruleDao.insert(rule, session);
 
     ActiveRuleDto activeRule = newActiveRule(profile, rule);
     tester.get(ActiveRuleDao.class).insert(activeRule, session);
@@ -217,12 +211,12 @@ public class RulesWebServiceTest {
 
     MockUserSession.set();
     WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "search");
-    request.setParam("q","S001");
-    request.setParam("activation","true");
-    request.setParam("qprofile",profile2.getKey().toString());
+    request.setParam("q", "S001");
+    request.setParam("activation", "true");
+    request.setParam("qprofile", profile2.getKey().toString());
     WsTester.Result result = request.execute();
 
-    result.assertJson(this.getClass(),"search_profile_active_rules.json");
+    result.assertJson(this.getClass(), "search_profile_active_rules.json");
   }
 
   @Test
@@ -240,14 +234,14 @@ public class RulesWebServiceTest {
       .setType("string")
       .setDescription("My small description")
       .setName("my_var");
-    ruleDao.addRuleParam(rule,param, session);
+    ruleDao.addRuleParam(rule, param, session);
 
     RuleParamDto param2 = RuleParamDto.createFor(rule)
       .setDefaultValue("other value")
       .setType("integer")
       .setDescription("My small description")
       .setName("the_var");
-    ruleDao.addRuleParam(rule,param2, session);
+    ruleDao.addRuleParam(rule, param2, session);
 
     ActiveRuleDto activeRule = newActiveRule(profile, rule);
     tester.get(ActiveRuleDao.class).insert(activeRule, session);
@@ -270,11 +264,10 @@ public class RulesWebServiceTest {
 
     WsTester.Result result = request.execute();
 
-    result.assertJson(this.getClass(),"search_active_rules_params.json");
+    result.assertJson(this.getClass(), "search_active_rules_params.json", false);
   }
 
 
-
   @Test
   public void get_tags() throws Exception {
     QualityProfileDto profile = newQualityProfile();
@@ -282,12 +275,12 @@ public class RulesWebServiceTest {
 
     RuleDto rule = newRuleDto(RuleKey.of(profile.getLanguage(), "S001"))
       .setTags(ImmutableSet.of("hello", "world"));
-    ruleDao.insert(rule,  session);
+    ruleDao.insert(rule, session);
 
     RuleDto rule2 = newRuleDto(RuleKey.of(profile.getLanguage(), "S002"))
       .setTags(ImmutableSet.of("java"))
       .setSystemTags(ImmutableSet.of("sys1"));
-    ruleDao.insert(rule2,  session);
+    ruleDao.insert(rule2, session);
 
     session.commit();
     tester.get(RuleService.class).refresh();
@@ -297,7 +290,7 @@ public class RulesWebServiceTest {
     WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "tags");
     WsTester.Result result = request.execute();
 
-    result.assertJson(this.getClass(),"get_tags.json");
+    result.assertJson(this.getClass(), "get_tags.json", false);
   }
 
   @Test
@@ -307,7 +300,7 @@ public class RulesWebServiceTest {
 
     RuleDto rule = newRuleDto(RuleKey.of(profile.getLanguage(), "S001"))
       .setNoteData("Note1");
-    ruleDao.insert(rule,  session);
+    ruleDao.insert(rule, session);
 
     session.commit();
     tester.get(RuleService.class).refresh();
@@ -317,14 +310,10 @@ public class RulesWebServiceTest {
     WsTester.TestRequest request = wsTester.newGetRequest("api/rules", "search");
     WsTester.Result result = request.execute();
 
-    System.out.println("result.outputAsString() = " + result.outputAsString());
-
-
-    result.assertJson(this.getClass(),"get_notes.json");
+    result.assertJson(this.getClass(), "get_notes.json");
   }
 
 
-
   private QualityProfileDto newQualityProfile() {
     return new QualityProfileDto()
       .setLanguage("java")
@@ -351,7 +340,7 @@ public class RulesWebServiceTest {
       .setEffortToFixDescription(ruleKey.repository() + "." + ruleKey.rule() + ".effortToFix");
   }
 
-  private ActiveRuleDto  newActiveRule(QualityProfileDto profile, RuleDto rule) {
+  private ActiveRuleDto newActiveRule(QualityProfileDto profile, RuleDto rule) {
     return ActiveRuleDto.createFor(profile, rule)
       .setInheritance("none")
       .setSeverity("BLOCKER");
diff --git a/sonar-server/src/test/java/org/sonar/server/search/BaseDocTest.java b/sonar-server/src/test/java/org/sonar/server/search/BaseDocTest.java
new file mode 100644 (file)
index 0000000..b6536f6
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with 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.search;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Maps;
+import org.junit.Test;
+
+import java.util.Collections;
+import java.util.Map;
+
+import static org.fest.assertions.Assertions.assertThat;
+import static org.fest.assertions.Fail.fail;
+
+public class BaseDocTest {
+
+  @Test
+  public void get() throws Exception {
+    Map<String,Object> fields = Maps.newHashMap();
+    fields.put("a_string", "foo");
+    fields.put("a_int", 42);
+    fields.put("a_null", null);
+    BaseDoc doc = new BaseDoc(fields) {
+    };
+
+    assertThat(doc.get("a_string")).isEqualTo("foo");
+    assertThat(doc.get("a_int")).isEqualTo(42);
+    assertThat(doc.get("a_null")).isNull();
+  }
+
+  @Test
+  public void get_fails_if_missing_field() throws Exception {
+    Map<String,Object> fields = Collections.emptyMap();
+    BaseDoc doc = new BaseDoc(fields) {
+    };
+
+    try {
+      doc.get("a_string");
+      fail();
+    } catch (IllegalStateException e) {
+     assertThat(e).hasMessage("Field a_string not specified in query options");
+    }
+  }
+}
index f809921a90188d9502844b36cd52bb06d08271b7..11070abef559f711e16a337c4765ce7ee6b8830c 100644 (file)
@@ -170,13 +170,17 @@ public class WsTester {
      * @param expectedJsonFilename name of the file containing the expected JSON
      */
     public Result assertJson(Class clazz, String expectedJsonFilename) throws Exception {
+      return assertJson(clazz, expectedJsonFilename, true);
+    }
+
+    public Result assertJson(Class clazz, String expectedJsonFilename, boolean strict) throws Exception {
       String path = clazz.getSimpleName() + "/" + expectedJsonFilename;
       URL url = clazz.getResource(path);
       if (url == null) {
         throw new IllegalStateException("Cannot find " + path);
       }
       String json = outputAsString();
-      JSONAssert.assertEquals(IOUtils.toString(url), json, true);
+      JSONAssert.assertEquals(IOUtils.toString(url), json, strict);
       return this;
     }
   }