Using JAVA to call OpenDaylight REST NBI to fetch all nodes

As with my previous post where I have noted about how to call OpenDaylight’s REST NBI using JQuery, here, I give a snippet of code to call the same service using JAVA which many people use to write apps on top of SDN Controllers.

You will need two additional jar’s to do this.

  1. Apache Codec for encoding the password in Base64.
  2. Jettison to use the JSONObject format for request/response.

Once you have included the above two jars in your classpath, here something you will have to do to get all ODL nodes:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.codec.binary.Base64;
import org.codehaus.jettison.json.JSONObject;

public class OpenDaylightHelper {

    public static JSONObject getNodes(String user, String password,
            String baseURL) {

        StringBuffer result = new StringBuffer();
        try {

            if (!baseURL.contains("http")) {
                baseURL = "http://" + baseURL;
            }
            baseURL = baseURL + "/controller/nb/v2/switchmanager/default/nodes";

            // Create URL = base URL + container
            URL url = new URL(baseURL);

            // Create authentication string and encode it to Base64
            String authStr = user + ":" + password;
            String encodedAuthStr = Base64.encodeBase64String(authStr
                    .getBytes());

            // Create Http connection
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();

            // Set connection properties
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Authorization", "Basic "
                    + encodedAuthStr);
            connection.setRequestProperty("Accept", "application/json");

            // Get the response from connection's inputStream
            InputStream content = (InputStream) connection.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    content));
            String line = "";
            while ((line = in.readLine()) != null) {
                result.append(line);
            }

            JSONObject nodes = new JSONObject(result.toString());
            return nodes;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

This call should fetch you all the nodes discovered in the topology of OpenDaylight.

More details about ODL NBI can be found on their Wiki.