Adding flows in OpenDaylight Using JAVA

Continuing my blog about getting the topology of OpenDaylight using Java, in this blog I have tried to give you ready to use java code to deploy a flow on OpenDaylight. As with the previous blog, you will need two jars in your classpath which are:

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

Now, once you have this in place, below code can be used to install a flow at the supplied OpenDaylight Controller.

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 boolean installFlow(JSONObject postData, String user,
            String password, String baseURL) {

        StringBuffer result = new StringBuffer();
        try {

            if (!baseURL.contains("http")) {
                baseURL = "http://" + baseURL;
            }
            baseURL = baseURL
                    + "/controller/nb/v2/flowprogrammer/default/node/OF/"
                    + postData.getJSONObject("node").get("id") + "/staticFlow/"
                    + postData.get("name");

            // 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("PUT");
            connection.setRequestProperty("Authorization", "Basic "
                    + encodedAuthStr);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            // Set Post Data
            OutputStream os = connection.getOutputStream();
            os.write(postData.toString().getBytes());
            os.close();

            // 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);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if ("success".equalsIgnoreCase(result.toString())) {
            return true;
        } else {
            return false;
        }
    }
}

Here is a snippet for invoking/calling the above code.

public static void main(String[] args) throws JSONException {
        //Sample post data.
        JSONObject postData = new JSONObject();
        postData.put("name", "SaurabhTestFlow");
        postData.put("nwSrc", "192.168.1.10");
        postData.put("nwDst", "192.168.1.11");
        postData.put("installInHw", "true");
        postData.put("priority", "500");
        postData.put("etherType", "0x800");
        postData.put("actions", new JSONArray().put("ENQEUE=2"));

        //Node on which this flow should be installed
        JSONObject node = new JSONObject();
        node.put("id", "00:00:00:76:54:54");
        node.put("type", "OF");
        postData.put("node", node);
        
        //Actual flow install
        boolean result = OpenDaylightHelper.installFlow(postData, "admin", "admin", "localhost:8080");
        
        if(result){
            System.out.println("Flow installed Successfully");
        }else{
            System.err.println("Failed to install flow!");
        }

    }

You can add as many parameters needed in the right format to above postData to install the correct flows in OpenDaylight. Find more details on parameters supported & all the REST api’s at http://opendaylight.nbi.sdngeeks.com.

A more detailed example with source code is available here.

Advertisements

17 thoughts on “Adding flows in OpenDaylight Using JAVA

  1. Regivaldo says:

    Hi, very good iniciative. I would to test the code, but in class, the line “postData.get(“name // Create URL = base URL + container” is incorret, right? Thank you.

    Like

  2. Regivaldo says:

    Yeah! Saurabh, I think that in main method, there others two pontual mistake:

    postData.put(“actionsw JSONArray().put(“ENQEUE=2”));
    postData.put(“nodede);

    I’m still try to work.

    Thank you.

    Like

  3. Thanks Manu for visiting the blog!

    About “Where to put the jars”.. All it matters is that those jars/classes are in your classpath. There are multiple ways to do that & depends on your project structure. (For maven you need the dependency, for java or web project it could be in WEB-INF/lib)

    For plain vanilla java program with main method you can probably do java -cp , class_with_main_method

    Like

    • Thanks for visiting the blog Vahid!

      To install a drop traffic flow, you just need to change the input in postData json in your calling method. Something like:

      postData.put(“actions”, new JSONArray().put(“DROP”));

      Let me know if you are still stuck!

      Like

      • Vahid says:

        Very thanks for reply.
        i’m not prefessional in ODL,
        i dont need to Activator.java,pom.xml,….
        i dont need to import library?

        thank you

        Like

  4. There are two ways to do it.

    1. Using OpenDaylight NBI’s
    2. Building a plugin inside OpenDaylight.

    This example is for the first approach, hence you don’t need activators, pom etc.

    This can be simply run as a java program from command line.

    Like

  5. Dimitris says:

    Hello team !!Saurabh Agarwal very good work, well done.

    I tried to run your program but i get an error response code 500 for my URL so that i cannot install the flow.Specifically i get this error:

    java.io.IOException: Server returned HTTP response code: 500 for URL: http://192.168.56.101:8080/controller/nb/v2/flowprogrammer/default/node/OF/00:00:00:00:00:00:00:01/staticFlow/flow1
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1403)
    at handoff.Flows.installFlow(Flows.java:53)
    at handoff.Handoff.main(Handoff.java:30)
    Failed to install flow!

    Can anyone help me?I dont why my URL is incorrect.
    The other exception is on line : InputStream content = connection.getInputStream();

    With my best regards,
    Jim.

    Like

    • Hi, thanks for visiting the blog and trying it out.

      500 generally means the resource is not available. Can you make sure that OpenDaylight NBI’s are available at 192.168.56.101. One quick way would be to use postman or poster browser plugin to do the same thing.

      Sorry for delayed response. Hope it helps, else let me know.

      Like

      • dimitris says:

        Saurabh thanks for your response.
        I normally install flows using Opendaylight web interface(localhost:8080).The problem after debugging my program is at line “OutputStream os = connection.getOutputStream();” on setting post data..Maybe there is a connection problem..

        PS: I wonder if your code is completed after uploading it on your blog or missing some words-letters.I would appreciate if you sent me your code to my email.I simply want to install a flow in my Openflow switch using JAVA and see my flow on my Opendaylight controller.

        My best regards.

        Like

    • Edu says:

      Hi Saurabh, thank you very much for you aportation.

      A question that I have is the following:
      If we want to access to:
      baseURL = baseURL + “/controller/nb/v2/flowprogrammer/default/node/OF/00:00:00:00:00:00:00:01/

      in the karaf version of OpenDayLight Helium, do you know witch features do we have to install?
      Becouse I cannot succed to implement the flows in the kafaf version.

      Thanks you!

      Like

  6. vikash says:

    Hello Saurav,

    do you have any reference how opendaylight manage network to docker Container service,

    with multiple Virtual switch

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s