JavaでZabbix API叩いてみた

スマートフォン買ったので勉強がてらAndroid版ざびたんウィジェット作ろうかと、テスト用クラスを作ってみました。



こんな感じで実行すると

package jp.mikeda.zabbix;

public class ZabbixApiTest {
  public static void main(String[] args) {
    ZabbixApi zabbixApi = new ZabbixApi("http://<SERVER>/zabbix/api_jsonrpc.php");

    try {
      zabbixApi.auth("<USER>", "<PASSWORD>");
      ZabbixApiHostGroup hostgroup = new ZabbixApiHostGroup(zabbixApi);
      for(String name: hostgroup.getNames()){
        System.out.println(name);
      }
    } catch (ZabbixApiException e) {
      System.err.println(e.getMessage());
      e.printStackTrace();
    }
  }

}

ホストグループのリストが取れます。

Linux servers
Zabbix servers

ソースコード

本体

callApiメソッドが全てです。
JSON関連のクラスが例外はきまくってめんどうなので、もうちょっとごかましたいところ。
このあたりが必要です(EclipseAndroidアプリ作ってればデフォルトで入ってます。もう1つくらいあったような)
http://hc.apache.org/downloads.cgi
http://commons.apache.org/codec/download_codec.cgi
https://github.com/douglascrockford/JSON-java/blob/master/JSONObject.java

package jp.mikeda.zabbix;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ZabbixApi {
  private String url;
  private String authId;

  public ZabbixApi(String url){
    this.url = url;
  }

  public void auth(String user, String password) throws ZabbixApiException{
    authId = null;

    JSONObject params = new JSONObject();
    try {
      params.put("user", user);
      params.put("password", password);
    } catch (JSONException e) {
      throw new ZabbixApiException(e.getMessage());
    }

    authId = getString("user.authenticate", params);
  }

  public String getString(String method , JSONObject params) throws ZabbixApiException{
    JSONObject responseJson = callApi(method, params);
    try {
      return responseJson.getString("result");
    } catch (JSONException e) {
      throw new ZabbixApiException(e.getMessage());
    }
  }

  public JSONArray getJSONArray(String method , JSONObject params) throws ZabbixApiException{
    JSONObject responseJson = callApi(method, params);
    try {
      return responseJson.getJSONArray("result");
    } catch (JSONException e) {
      throw new ZabbixApiException(e.getMessage());
    }
  }

  public JSONObject callApi(String method, JSONObject params) throws ZabbixApiException {
    // リクエスト用JSON作成
    JSONObject requestJson = new JSONObject();
    try {
      requestJson.put("auth",    authId);
      requestJson.put("method",  method);
      requestJson.put("id",      1);
      requestJson.put("jsonrpc", "2.0");
      requestJson.put("params",  params);
    } catch (JSONException e) {
      throw new ZabbixApiException(e.getMessage());
    }

    // HTTP POST
    HttpResponse httpResponse;
    HttpPost httpPost = new HttpPost(this.url);
    String responseBody;
    try {
      httpPost.setHeader("Content-Type", "application/json-rpc");
      httpPost.setHeader("User-Agent",   "Zabbitan Widget");
      httpPost.setEntity(new StringEntity(requestJson.toString()));

      DefaultHttpClient client = new DefaultHttpClient();
      httpResponse = client.execute(httpPost);
      responseBody = EntityUtils.toString(httpResponse.getEntity());
    } catch (Exception e) {
      throw new ZabbixApiException("HTTP Request Error");
    }

    // HTTP エラー処理
    if( httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK){
      throw new ZabbixApiException("HTTP Error : " + responseBody);
    }

    // JSON Objectの取り出し
    JSONObject responseJson;
    try {
      responseJson = new JSONObject(responseBody);
    } catch (Exception e) {
      throw new ZabbixApiException(e.getMessage());
    }

    // APIエラー処理
    if(responseJson.has("error")) {
      String message;
      try {
        message = "API Error : " + responseJson.getJSONObject("error").toString();
      } catch (JSONException e) {
        throw new ZabbixApiException(e.getMessage());
      }
      message += "\nRequest:" + requestJson.toString();
      throw new ZabbixApiException(message);
    }

    return responseJson;
  }

}
例外

とりあえず・・・

package jp.mikeda.zabbix;

public class ZabbixApiException extends Exception {
  public ZabbixApiException(String message){
    super(message);
  }
}
ラッパー

そのままでは使いづらいのでラッパークラスが必要だと思います。
とりあえずテスト用のホストグループ関連クラス。

package jp.mikeda.zabbix;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ZabbixApiHostGroup {
  private ZabbixApi zabbixApi;

  public ZabbixApiHostGroup(ZabbixApi zabbixApi){
    this.zabbixApi = zabbixApi;
  }
  public String[] getNames() throws ZabbixApiException {
    String[] groups;

    try {
      JSONObject params = new JSONObject();
      params.put("output", "extend");

      JSONArray responseJSON = zabbixApi.getJSONArray("hostgroup.get", params);
      int count = responseJSON.length();
      groups = new String[count];
      for(int i=0;i<count;i++){
        groups[i] = responseJSON.getJSONObject(i).getString("name");
      }
    } catch (JSONException e) {
      throw new ZabbixApiException(e.getMessage());
    }

    return groups;
  }
}