IBM Intelligent Operations Center REST Client

I made a simple command line REST client while making the IBM Traffic Operations Center demo. Although the REST client was done for specific IOC demo, I think it can be used in any IOC demo that uses REST or it can be used to just poke around the IOC REST API.

The client was developed with Java and Eclipse IDE. It uses third-party components Apache HTTPComponents, Jackson for JSON processing and some Apache Commons libraries.

To anyone who’s interested, here is the client: IOCRESTClient.zip. Change the extension to .jar and it’s ready to be executed using arguments: <USERNAME> <PASSWORD> <SERVER> <SERVICEURL> <METHOD> <CONTENT or -fJSONFILENAME>. For example, the following command retrieves all data sources defined in IOC.

java -jar IOCRESTClient.jar wpsadmin password iocweb.ibmplatform.com /ibm/ioc/api/datasource-service/datasources GET ""

The main program parses argument, calls generic REST client class and pretty-prints the result to console.

package ioc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class IOCClient {

	public static void main(String[] args) {

		try {
			boolean test = false;

			if (test) {
				args = new String[6];
				args[0] = "wpsadmin";
				args[1] = "password";
				args[2] = "iocweb.ibmplatform.com";
				args[3] = "/ibm/ioc/api/datasource-service/datasources";
				args[4] = "GET";
				args[5] = "";

			}

			if (args == null || args.length < 6) {
				System.out
						.println("Usage params: <USERNAME> <PASSWORD> <SERVER> <SERVICEURL> <METHOD> <CONTENT or -fJSONFILENAME>");

				return;
			}

			String userName = args[0];
			String password = args[1];
			String server = args[2];
			String url = args[3];
			String method = args[4];
			String content = args[5];

			if (content.startsWith("-f")) {
				content = content.replace("-f", "");
				BufferedReader br = new BufferedReader(
						new FileReader(new File(content)));
				content = "";
				String line = br.readLine();
				while (line != null) {
					content = content + line;
					line = br.readLine();
				}
				br.close();
			}

			RESTClient.SERVER_HOST = server;
			RESTClient.USER_NAME = userName;
			RESTClient.PASSWORD = password;

			String response;

			response = RESTClient.call(url, method, "application/json", content);
			if (response != null && !response.equals("")) {
				printRestResponse(response);
			}

			if (response != null && !response.equals("")) {
				ObjectMapper mapper = new ObjectMapper();
				JsonNode actualObj = mapper.readValue(response, JsonNode.class);
				JsonNode node = actualObj.get("OBJECTID");
				if (node != null) {
					System.exit(node.asInt());
				}
			}
			System.exit(0);
		} catch (Exception e) {
			System.out.println("ERROR: " + e.toString());
			//e.printStackTrace();
		}

	}

	private static void printRestResponse(String response) {
		try {
			ObjectMapper mapper = new ObjectMapper();
			Object json = mapper.readValue(response, Object.class);

			String indented = mapper.writerWithDefaultPrettyPrinter()
					.writeValueAsString(json);
			System.out.println(indented);

		} catch (Exception e) {
			System.out.println(e.toString());
			System.out.println(response);
		}

	}

}

The REST client class is somewhat generic. It omits peer authentication, so it may not be entirely secure.

package ioc;

import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;

public class RESTClient {

	public static String SERVER_HOST = "-";
	public static int SERVER_PORT = 443;
	public static String USER_NAME = "-";
	public static String PASSWORD = "-";

	public static String call(String url, String method, String contentType,
			String content)

	throws Exception {
		DefaultHttpClient httpclient = null;
		try {
			httpclient = new DefaultHttpClient();
			Scheme http = new Scheme("http", 80,
					PlainSocketFactory.getSocketFactory());

			SSLContext sslcontext = SSLContext.getInstance("SSL");
			sslcontext.init(null, getTrustingManager(),
					new java.security.SecureRandom());
			SSLSocketFactory sf = new SSLSocketFactory(sslcontext,
					SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			Scheme https = new Scheme("https", 9443, sf);

			httpclient.getConnectionManager().getSchemeRegistry().register(http);
			httpclient.getConnectionManager().getSchemeRegistry().register(https);

			HttpHost targetHost = new HttpHost(SERVER_HOST, SERVER_PORT, "https");

			httpclient.getCredentialsProvider().setCredentials(
					new AuthScope(targetHost.getHostName(), targetHost.getPort()),
					new UsernamePasswordCredentials(USER_NAME, PASSWORD));

			// Create AuthCache instance
			AuthCache authCache = new BasicAuthCache();
			// Generate BASIC scheme object and add it to the local
			// auth cache
			BasicScheme basicAuth = new BasicScheme();
			authCache.put(targetHost, basicAuth);
			// Add AuthCache to the execution context
			BasicHttpContext localcontext = new BasicHttpContext();
			localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

			HttpResponse response = null;
			HttpRequest request = null;
			HttpEntity entity = null;
			if (method.equalsIgnoreCase("post")) {
				StringEntity myEntity = new StringEntity(content);
				myEntity.setContentType(contentType);

				HttpPost httppost = new HttpPost(url);
				httppost.setEntity(myEntity);
				request = httppost;

			}
			if (method.equalsIgnoreCase("get")) {
				HttpGet httpget = new HttpGet(url);
				request = httpget;

			}

			if (method.equalsIgnoreCase("delete")) {
				HttpDelete httpdel = new HttpDelete(url);
				request = httpdel;
			}
			response = httpclient.execute(targetHost, request, localcontext);
			entity = response.getEntity();

			System.out.println(request.getRequestLine().toString());
			System.out.println(response.getStatusLine().toString());
			if (entity != null) {
				return EntityUtils.toString(entity);
			} else {
				return "";
			}
		} finally {
			// When HttpClient instance is no longer needed,
			// shut down the connection manager to ensure
			// immediate deallocation of all system resources
			httpclient.getConnectionManager().shutdown();
		}
	}

	/*
	 * Code from
	 * http://stackoverflow.com/questions/2308774/httpget-with-https-sslpeerunverifiedexception?lq=1
	 */
	private static TrustManager[] getTrustingManager() {
		TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
			@Override
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return null;
			}

			@Override
			public void checkClientTrusted(X509Certificate[] certs, String authType) {
				// Do nothing
			}

			@Override
			public void checkServerTrusted(X509Certificate[] certs, String authType) {
				// Do nothing
			}

		} };
		return trustAllCerts;
	}

}

Here is the Eclipse project file: IOCRESTClient_project.zip.

Leave a Reply

Your email address will not be published. Required fields are marked *