// The Client sessions package
import com.thetransactioncompany.jsonrpc2.client.*;

// The Base package for representing JSON-RPC 2.0 messages
import com.thetransactioncompany.jsonrpc2.*;

// The JSON Smart package for JSON encoding/decoding (optional)
import net.minidev.json.*;

// For creating URLs
import java.net.*;

import java.text.*;
import java.util.*;


public class Benchmark {

	public static void main(String[] args) {
		
		// Force Basic authorization
		final String rpcuser ="admin"; // change to your own username
		final String rpcpassword ="xxxxxxx"; // change to your own password
		Authenticator.setDefault(
			new Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication (rpcuser, rpcpassword.toCharArray());
				}
			}
		);

		// Creating a new session to a JSON-RPC 2.0 web service at a specified URL

		// The JSON-RPC 2.0 server URL
		URL serverURL = null;
		try {
			serverURL = new URL("http://192.168.11.111/command-api"); // change to your own address
		} catch (MalformedURLException e) {
			e.printStackTrace(); // need better information
		}

		// Create new JSON-RPC 2.0 client session
		JSONRPC2Session mySession = new JSONRPC2Session(serverURL);

		// Once the client session object is created, you can use to send a series
		// of JSON-RPC 2.0 requests and notifications to it.

		// Construct new request

		String method = "runCmds";
		Map<String,Object> cmdParam = new HashMap<String,Object>();
		cmdParam.put("version", 1);
		List cmds = new LinkedList();
		cmds.add("show version");  // 1st request
		cmds.add("show vlan");   // 2nd request
		cmdParam.put("cmds", cmds);
		cmdParam.put("format", "json");
		int requestID = 0; 
		JSONRPC2Request request = new JSONRPC2Request(method, cmdParam, requestID);

		long t1 = System.nanoTime(); // timer set
		
		// Send request
		JSONRPC2Response response = null;

		try {
			response = mySession.send(request);

		} catch (JSONRPC2SessionException e) {
			System.err.println(e.getMessage());
			System.out.println("something happen...");
		}

		long t2 = System.nanoTime(); // timer set
		System.out.println("Time(ns) "+(t2-t1));

		// Print response result / error
		if (response.indicatesSuccess()) {
			JSONArray resp = (JSONArray)response.getResult();

			JSONObject obj = (JSONObject)resp.get(0);
			System.out.println(obj.get("version"));

			obj = (JSONObject)resp.get(1);
			JSONObject vlans = (JSONObject)obj.get("vlans");
			JSONObject vlan = (JSONObject)vlans.get("1");
			System.out.println(vlan);
			
		} else {
			System.out.println(response.getError().getMessage());
		}
	}
}

