如何使用 Sonar 的 Web 服务 java 客户端持久化 Sonar 属性?
[编辑:我现在意识到 Web Service Client 不适用于开发插件;而应该使用 Sonar 的 API 中的其他类。请参阅我接受的答案。]
我打算为声纳制作一个插件。与此同时,我正在熟悉 Sonar 的 API,尤其是 Sonar 的 Web 服务 Java 客户端。我试图弄清楚如何保留声纳属性。我写了以下代码:
package testers;
import org.sonar.wsclient.Sonar;
import org.sonar.wsclient.services.Property;
import org.sonar.wsclient.services.PropertyCreateQuery;
import org.sonar.wsclient.services.PropertyQuery;
public class PropertyPersister {
public static Sonar localSonar;
public static Property sonarStartTime;
public static PropertyQuery findStartTime;
public static Property testProperty;
public static PropertyQuery findTestProperty;
public static String testKey = "testKey";
public static String testValue = "testValue";
/**
* @param args
*/
public static void main(String[] args) {
//localSonar = Sonar.create("http://localhost:9000");//pointed to my instance of Sonar
//EDIT: using this line instead, but it still gives the same stack trace.
localSonar = Sonar.create("http://localhost:9000", "admin", "admin");//pointed to my instance of Sonar
findStartTime = PropertyQuery.createForKey("sonar.core.startTime");//creating query for a key I know exists
sonarStartTime = localSonar.find(findStartTime);//retrieve property object from my Sonar's database
System.out.println(sonarStartTime);//print out this object
PropertyCreateQuery testCreateQuery = new PropertyCreateQuery(testKey, testValue);//Query to create test property
localSonar.create(testCreateQuery);//With this line, I'm trying to persist my test property
findTestProperty = PropertyQuery.createForKey(testKey);//creating query for retrieving test property
testProperty = localSonar.find(findTestProperty);//line 36: retrieve property object from my Sonar's database
System.out.println(testProperty);//print test property
}
}
此代码打印出已经存在的 sonarStartTime 属性:
[sonar.core.startTime:2013-03-14T08:05:42-0700]
然后是倒数第二行抛出的空指针异常。异常消息包括:
org.sonar.wsclient.unmarshallers.UnmarshalException: Can not parse the response of query /api/properties/testKey?: {"err_code":404,"err_msg":"Property not found: testKey"}
使用 MySQL 工作台,我确认确实,我的测试属性从未持久化。显然,我正在以错误的方式解决这个问题。所以,重申我的问题,如何使用 Sonar 的 Web 服务 java 客户端在 Sonar 中保留一个属性?
[编辑] 这是带有堆栈跟踪的完整控制台输出:
[sonar.core.startTime:2013-03-14T08:05:42-0700]
Exception in thread "main" org.sonar.wsclient.unmarshallers.UnmarshalException: Can not parse the response of query /api/properties/testKey?: {"err_code":404,"err_msg":"Property not found: testKey"}
at org.sonar.wsclient.Sonar.find(Sonar.java:56)
at testers.PropertyPersister.main(PropertyPersister.java:36)
Caused by: java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to java.util.ArrayList
at org.sonar.wsclient.JdkUtils.getArraySize(JdkUtils.java:87)
at org.sonar.wsclient.unmarshallers.AbstractUnmarshaller.toModel(AbstractUnmarshaller.java:34)
at org.sonar.wsclient.Sonar.find(Sonar.java:54)
... 1 more