Java use Zabbix sample __java

Source: Internet
Author: User
Tags auth documentation getmessage

1. Create Class Zabbixrequest

public class Zabbixrequest {
	String jsonrpc = "2.0";

	String method;

	String Auth;

	Integer ID;

	

	Public String Getjsonrpc () {return
		jsonrpc;
	}

	public void Setjsonrpc (String jsonrpc) {
		this.jsonrpc = jsonrpc;
	}


	Public String GetMethod () {return method
		;
	}

	public void Setmethod (String method) {
		This.method = method;
	}

	Public String GetAuth () {return
		auth;
	}

	public void Setauth (String auth) {
		this.auth = auth;
	}

	Public Integer GetId () {return
		ID;
	}

	public void SetId (Integer id) {
		this.id = ID;
	}

}

2. Create Class Zabbixrequestobject

public class Zabbixrequestobject extends Zabbixrequest {
	
	private Object params;

	Public Object Getparams () {return
		params;
	}

	public void SetParams (Object params) {
		this.params = params;
	}
	
}

3. Create Class Zabbixrequestparams

Import Java.util.HashMap;
Import Java.util.Map;

public class Zabbixrequestparams extends Zabbixrequest {
	
	private map<string, object> params = new hashmap<st Ring, object> ();

	Public map<string, Object> Getparams () {return
		params;
	}

	public void SetParams (map<string, object> params) {
		this.params = params;
	}
	
	
	public void Putparam (String key, Object value) {
		params.put (key, value);
	}

	Public Object Removeparam (String key) {return
		params.remove (key);
	}
}

4. Create Class Zabbixrequestbuilder

Import Java.util.concurrent.atomic.AtomicInteger;

	 	public class Zabbixrequestbuilder {private static final Atomicinteger NextID = new Atomicinteger (1);
		
	 	Zabbixrequest request;
	 	Zabbixrequestobject obj= new Zabbixrequestobject ();
	 	
		Zabbixrequestparams param = new Zabbixrequestparams ();
			Private Zabbixrequestbuilder (String str) {if ("obj". Equals (str)) {this.request= obj;
			}else{this.request = param;
		} static public Zabbixrequestbuilder Newbuilder (String str) {return new Zabbixrequestbuilder (str);
		static public Zabbixrequestbuilder Newbuilder () {return new Zabbixrequestbuilder ("param");
			Public Zabbixrequest Build () {if (Request.getid () = null) {Request.setid (nextid.getandincrement ());
		return request;
			Public Zabbixrequestbuilder version (String version) {REQUEST.SETJSONRPC (version);
		return this; Public Zabbixrequestbuilder paramentry (String key, Object value) {if (Request InstAnceof zabbixrequestparams) {(zabbixrequestparams) request). Putparam (key, value);
		return to this; }/** * does not necessary to call this method. 
		 If Don not set ID, Zabbixapi'll auto set request Auth ...
			* @param auth * @return/public zabbixrequestbuilder auth (String auth) {Request.setauth (auth);
		return this;
			Public Zabbixrequestbuilder Method (String method) {Request.setmethod (method);
		return this; }/** * does not necessary to call this method.
		 If Don not set ID, Requestbuilder'll auto generate.
			* @param ID * @return/public zabbixrequestbuilder ID (Integer ID) {Request.setid (ID);
		return this; Public Zabbixrequestbuilder object (object obj) {if (Request instanceof Zabbixrequestobject) {(zabbixreque
			stobject). SetParams (obj);
			
		return to this; }
}

5. Common methods


public class Zabbixshare {private static final Logger Logger = Loggerfactory.getlogger (Zabbixshare.class);

	@Autowired Environment env;
    
	
	Private String auth;
	Public String GetAuth () {return auth;
	} public void Setauth (String auth) {This.auth = auth;
		 public Boolean login () throws URISyntaxException {String uname =env.getproperty ("Zabbix_uname");
		 
		String upwd =env.getproperty ("zabbix_upwd"); Zabbixrequest request = Zabbixrequestbuilder.newbuilder (). Paramentry ("user", uname). Paramentry ("password", upwd).
		Method (' User.login '). Build ();
		Jsonobject response = call (request);
		String auth = response.getstring ("result");
			if (auth!= null &&!auth.isempty ()) {This.setauth (auth);
			Logger.info ("Login Zabbix success!");
		return true;
		} logger.info ("Login Zabbix failed!");
	return false;
	 /** * Query Items * @param hostName hostip * @param searchkey Query key * @param groupname Group name * @return Item List * @throws ExceptIon Exception */public jsonobject queryitems (String hostname,string searchkey,string groupname) throws exception{
		Response = NULL;
		Jsonobject search = new Jsonobject ();
	    Logger.info ("Queryitems--searchkey:" +searchkey+ "HostName:" +hostname+ "GroupName:" +groupname);
		Search.put ("Key_", Searchkey); Zabbixrequest request = Zabbixrequestbuilder.newbuilder (). Method ("Item.get"). Paramentry ("Output", "extend"). Para
		 Mentry ("host", HostName). Paramentry ("Search", search)//.paramentry ("group", GroupName). Build ();
		Response = call (request);
	return response; /** * Query Host * @param hostName HostIP * @return Host list * @throws Exception exception/public jsonobject Queryhos
		T (String hostName) throws exception{jsonobject response = null;
			 if (login ()) {Logger.info ("Queryhost--hostname:" +hostname);
			 Jsonobject search = new Jsonobject ();
			Search.put ("host", HostName); Zabbixrequest request = Zabbixrequestbuilder.newbuilder (). Method ("HoSt.get "). Paramentry (" Output "," extend "). Paramentry (" filter ", search). Build ();
		Response = call (request);
	return response; /** * Query Applications * @param hostId hostId * @param name Query name * @return Applications list * @throws Exception different
		Constant */Public jsonobject queryapplications (String hostid,string name) throws exception{jsonobject = null;
		Jsonobject search = new Jsonobject ();
		Search.put ("key", name);
		Logger.info ("Queryapplications--hostid:" +hostid);
				Zabbixrequest request = Zabbixrequestbuilder.newbuilder (). Method ("Application.get"). Paramentry ("Output", "extend")
		 . Paramentry ("Hostids", HostId). Paramentry ("filter", search). Build ();
		 Response = call (request);
		Logger.info (String.Format ("Queryapplications response:%s", response.tojsonstring ());
	return response; /** * Hostinterface.get * @param hostId hostId * @return hostinterface list * @throws Exception/Public J Sonobject Queryhostinterface(String hostId) throws exception{jsonobject response = null;
		Logger.info ("Queryhostinterface--hostid:" +hostid); Zabbixrequest request = Zabbixrequestbuilder.newbuilder (). Method ("Hostinterface.get"). Paramentry ("Output", "Extend
		 "). Paramentry (" Hostids ", HostId). Build ();
		 Response = call (request);
		Logger.info (String.Format ("Queryhostinterface response:%s", response.tojsonstring ());
	return response; Jsonobject Call (Zabbixrequest request) throws URISyntaxException {if (Request.getauth () = null) {req
		Uest.setauth (auth);
		} String URL =env.getproperty ("Zabbix_url"); try {httpurirequest HttpRequest = Org.apache.http.client.methods.RequestBuilder. Post (). Seturi (New URI (Url.trim () ). AddHeader ("Content-type", "Application/json"). Setentity (New stringentity (Request), "json.tojsonstring"
			). build ();
			Closeablehttpclient Httpclient=httpclients.custom (). build (); Closeablehttpresponse response = Httpclient.execute(HttpRequest);
			httpentity entity = response.getentity ();
			byte[] data = Entityutils.tobytearray (entity);
		Return (Jsonobject) json.parse (data);
		catch (IOException e) {throw new RuntimeException ("Defaultzabbixapi call exception!", e); }/** * Converts the argument into the required format * @param user_time * @return * @throws Exception * * public static St
		   Ring Datetotimestamp (String time_from) throws Exception {Calendar calendar = calendar.getinstance (); 
			   Switch (time_from) {case "D": Calendar.add (Calendar.day_of_year,-1);
	       Break
	    	   Case "W": Calendar.add (Calendar.week_of_year,-1);
	       Break
			   Case "M": Calendar.add (Calendar.month,-1);
	       Break
			   Case "H": Calendar.add (CALENDAR.HOUR,-12);
			Break
				Default:calendar.set (Calendar.hour_of_day, Calendar.get (calendar.hour_of_day)-1);
			Break
	       } String re_time = null; SimpleDateFormat SDF = new SimpledaTeformat ("Yyyy-mm-dd HH:mm:ss");
	       Date D;
		   D = Sdf.parse (Sdf.format (Calendar.gettime ()));
		   Long L = d.gettime ();
		   String str = string.valueof (l);
	       Re_time = str.substring (0, 10);
	   return re_time; /** * Query monitoring items based on monitor ID and host ID * @param monitorkeys (MUST) monitor keys * @param hostids host IDs * @param outputs output field name * @re  Turn the Eligible items JSON * @throws monitorexception/public jsonobject queryitemsbykeyshostids (collection<string> Monitorkeys, collection<string> hostids, String ... outputs) throws Monitorexception {try {jsonobject fil
			ter = new Jsonobject ();
			Filter.put ("Key_", Monitorkeys);
			if (Collectionutils.isnotempty (Hostids)) {filter.put ("HostID", hostids); } Zabbixrequestbuilder builder = Zabbixrequestbuilder.newbuilder (). Method ("Item.get")//. Paramentry ("Output", Arra Yutils.isempty (outputs)? "Extend": outputs)//. Paramentry ("filter", filter)//. Paramentry ("Selectinterfaces", New string[]{"InterfaceID", "HostID", "IP", "type"}). Paramentry ("Selecttriggers", New string[]{"Triggerid", "expression", "state" , "status", "value"}). Paramentry ("Selecthosts", new string[] {"Host", "HostID"});//Zabbixrequest request = Bui
			Lder.build (); Logger.info (String.Format ("Queryitemsbykeyshostids >>>>request:%s"),
			Tostringbuilder.reflectiontostring (request));
			Jsonobject JSON = call (request);
			Logger.info (String.Format ("Queryitemsbykeyshostids <<<response:%s", json.tojsonstring ());
		return JSON; The catch (Exception e) {logger.error ("Query monitoring information failed.")
			", e); throw new Monitorexception ("Monitoring information does not exist.")
		"); /** * Based on monitor key query template monitor * @param monitorkeys * @param outputs * @return * @throws monitorexception/PU Blic jsonobject Querytemplateitemsbykeys (collection<string> monitorkeys, String ... outputs) throws
			monitorexception{try {jsonobject filter = new Jsonobject ();
			Filter.put ("Key_", Monitorkeys); ZabbixrequestBuilder Builder = Zabbixrequestbuilder.newbuilder (). Method ("Item.get")//. Paramentry ("Output", Arrayutils.isempty ( Outputs)?  "Extend": outputs)//. Paramentry ("filter", filter)//. Paramentry ("templated", True);//Zabbixrequest Request
			= Builder.build (); Logger.info (String.Format ("Querytemplateitemsbykeys >>>>request:%s"),
			Tostringbuilder.reflectiontostring (request));
			Jsonobject JSON = call (request);
			Logger.info (String.Format ("Querytemplateitemsbykeys <<<response:%s", json.tojsonstring ());
		return JSON; The catch (Exception e) {logger.error ("Query monitoring information failed.")
			", e); throw new Monitorexception ("Monitoring information does not exist.")
		"); /** * Query Host * Based on host name * @param hostnames host name * @param outputs output field name * @return Eligible host * @throws monitorexcept Ion */Public Jsonobject queryhostsbyhostnames (collection<string> hostnames, String ... outputs) throws Monitorexc eption {try {jsonobject jsonhostinterfaces = Queryinterfacesbyhostnames (hostNameS, "HostID");
			Jsonarray Hostarray = Jsonhostinterfaces.getjsonarray ("result");
			set<string> hostids = new hashset<string> ();
			for (int i = 0; i< hostarray.size (); i++) {Hostids.add (Hostarray.getjsonobject (i). getString ("HostID"));
			} if (Collectionutils.isempty (hostids)) {throw new Monitorexception ("host does not exist, hostnames:" + hostnames);
			} jsonobject filter = new Jsonobject ();
			Filter.put ("HostID", hostids); Zabbixrequest request = Zabbixrequestbuilder.newbuilder (). Method ("Host.get")//. Paramentry ("filter", filter)//. Paramentry ("Selectinterfaces", New string[]{"InterfaceID", "IP", "type", "HostID"})//. Paramentry ("Output", Arrayutil S.isempty (outputs)?
			"Extend": outputs)//. Build (); Logger.info (String.Format ("Queryhostsbyhostnames >>>>request:%s", tostringbuilder.reflectiontostring
			(request));

			Jsonobject JSON = call (request); Logger.info (String.Format ("Queryhostsbyhostnames <<<response:%s", JSon.tojsonstring ()));
		return JSON;
			catch (Exception e) {logger.error ("host does not exist:" + e.getmessage (), E); throw new Monitorexception ("host information does not exist.
		"); /** * through name, query template Details * @param name * @return * @throws urisyntaxexception/public Jsonobject Querytempl
		Atebyname (String name) throws urisyntaxexception{jsonobject response = null;
			if (login ()) {list<string> out = arrays.aslist (name);
			list<string> output = arrays.aslist ("Itemid", "name", "Key_");
			map<string,object> filter = new hashmap<string, object> ();
			Filter.put ("host", out);
					Zabbixrequest request = Zabbixrequestbuilder.newbuilder (). Method ("Template.get"). Paramentry ("Output", "extend")
			 . Paramentry ("Selectitems", Output). Paramentry ("filter", filter). build ();
		Response = call (request);
	return response; /** * through Itemid, query template details * @param name * @return * @throws urisyntaxexception/public Jsonobject Querytempla Tebyitemids (list&Lt String> Itemids, collection<string> Hostids, string...outputs) throws urisyntaxexception{JSONObject response
		= NULL; Zabbixrequest request = Zabbixrequestbuilder.newbuilder (). Method ("Template.get"). Paramentry ("Itemids", Itemids). Paramentry ("Hostids", Hostids). Paramentry ("Selecthosts", New string[]{"HostID", "host"}). Paramentry ("Output", Ar Rayutils.isempty (outputs)?
		"Extend": outputs). build (); Logger.info (String.Format ("Querytemplatebyitemids >>>>request:%s"),
		Tostringbuilder.reflectiontostring (request));
		Response = call (request);
		Logger.info (String.Format ("Querytemplatebyitemids <<<response:%s", response.tojsonstring ());
	return response; Private Jsonobject Queryinterfacesbyhostnames (collection<string> hostnames, String ... outputs) throws MonitorE
			xception{try {jsonobject filter = new Jsonobject ();
			Filter.put ("IP", hostnames); Zabbixrequest request = Zabbixrequestbuilder.newbuilder (). method("Hostinterface.get")//. Paramentry ("filter", filter)//. Paramentry ("Output", arrayutils.isempty (outputs)?
			"Extend": outputs)//. Build (); Logger.info (String.Format ("Queryinterfacesbyhostnames >>>>request:%s"),
			Tostringbuilder.reflectiontostring (request));

			Jsonobject JSON = call (request);
			Logger.info (String.Format ("Queryinterfacesbyhostnames <<<response:%s", json.tojsonstring ());
		return JSON;
			catch (Exception e) {logger.error ("host IP does not exist:" + e.getmessage (), E); throw new Monitorexception ("Host IP does not exist.
		"); }
	}
}


API Documentation Https://www.zabbix.com/documentation/2.2/manual/api
Docs http://www.zabbix.org/wiki/Docs/api/libraries

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.