package util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import constant.ConfigConstant;
import ftl.FtlClass;
/**
* @author java_guoenzhou@163.com
*
*/
public class ZabbixUtil {
static String authID = null;
//用户名
static String user = ConfigConstant.ZABBIX_USER;
//密码
static String password = ConfigConstant.ZABBIX_PASSWORD;
//请求URL
static String url = ConfigConstant.ZABBIX_URL;
//zabbix API 版本
static String version = ConfigConstant.ZABBIX_VERSION;
static{
authID = user_login();
}
/**
* 登录验证获取auth
* @return
*/
public static String user_login(){
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("user", user);
paramMap.put("password", password);
String result = execute("user.login",paramMap);
@SuppressWarnings("unchecked")
Map<String, Object> jsonMap = (Map<String, Object>)JSONObject.parse(result);
String authID =String.valueOf(jsonMap.get("result"));
System.out.println(authID);
return authID;
}
/**
* HTTP 请求
* @param jsonArgument
* @return
*/
public static String get_data(String jsonArgument ) {
try {
URL httpUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json-rpc");
// 表单参数
StringBuffer params = new StringBuffer();
params.append(jsonArgument);
byte[] bypes = params.toString().getBytes();
conn.getOutputStream().write(bypes);// 输入参数
//返回
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String result = reader.readLine();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 执行
* @param method 方法名称
* @param paramMap 模板参数集合
* @return
*/
public static String execute(String method,Map<String, Object> paramMap){
String basePath = FtlClass.class.getResource(version+"/").getPath();
try {
String temp = FreemarkerUtils.getTemplate(basePath, method, paramMap);
return get_data(temp);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param method 方法名称
* @param params 模板参数集合
* @return
*/
public static String execute(String method,String[] params){
String basePath = FtlClass.class.getResource(version+"/").getPath();
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("auth", authID);
paramMap.put("params", params);
try {
String temp = FreemarkerUtils.getTemplate(basePath, method, paramMap);
return get_data(temp);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws IOException {
//String result = execute("hostgroup.create",new String[]{"TEST3"});
//System.out.println(result);
}
}