RAPIFIRE

Blog

Management of 100s of Sensors with RAPIFIRE's Automation API

RAPIFIRE provides an HTTP automation API for efficiently managing in bulk many Iot Things. This example will use Apache's HttpComponents to call the API to create 100 thermometer things and users. The java class for this example assigns each user to a thermometer thing and sets the meta data of MaxTemp = 89.0 to each thermometer thing. Lastly it deletes the users and things to clean them up.

Okay let's get started. Do the following steps:

  • Create a RAPIFIRE account here

  • Create project and install httpclient jars to build library path with this maven POM dependency below. Alternatively download the directly jars from here

   <dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.1</version>
</dependency>  
  </dependencies>
  • Copy this class AutomationApp.java from below to your java IDE.
package rapifire.automationapi;

import java.io.IOException;  
import org.apache.http.HttpEntity;  
import org.apache.http.HttpResponse;  
import org.apache.http.auth.AuthScope;  
import org.apache.http.auth.UsernamePasswordCredentials;  
import org.apache.http.client.ClientProtocolException;  
import org.apache.http.client.CredentialsProvider;  
import org.apache.http.client.HttpClient;  
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.methods.HttpPut;  
import org.apache.http.entity.StringEntity;  
import org.apache.http.impl.client.BasicCredentialsProvider;  
import org.apache.http.impl.client.HttpClientBuilder;  
import org.apache.http.util.EntityUtils;

/**
 * Example on how to use the Rapifire automation API.
 *
 */
// http://hc.apache.org/httpcomponents-client-ga/httpclient/dependency-info.html

public class AutomationApp {

    static final int NUM_THINGS = 100;
    static final int NUM_USERS = NUM_THINGS;

    public AutomationApp() {

    }

    public String getThingMetadataKey(String thingId, String key) {
        String returnValue = "";
        try {

            System.out.println("getThingMetadata(" + thingId + ", " + key + ")");

            CredentialsProvider provider = new BasicCredentialsProvider();
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("marktesterg@gmail.com",
                    "123456");
            provider.setCredentials(AuthScope.ANY, credentials);
            HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
            HttpResponse response = client
                    .execute(new HttpGet("http://api.rapifire.com/api/v1/things/" + thingId + "/meta/" + key));
            int code = response.getStatusLine().getStatusCode();

            if (code != 200) {
                return "ERROR code: " + code;
            }

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String returnString = EntityUtils.toString(entity);
                // System.out.println(returnValue);
                returnValue = this.getMsgValue("value", returnString);
                EntityUtils.consume(entity);
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return "ERROR ClientProtocolException";
        } catch (IOException e) {
            e.printStackTrace();
            return "ERROR IOException";
        }
        return returnValue;
    }

    public int getMyDeveloperId() {
        int returnDeveloperId = 0;
        try {

            System.out.println("getMyUserDetails()");

            CredentialsProvider provider = new BasicCredentialsProvider();
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("marktesterg@gmail.com",
                    "123456");
            provider.setCredentials(AuthScope.ANY, credentials);
            HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
            HttpResponse response = client.execute(new HttpGet("http://api.rapifire.com/api/v1/myself"));

            int code = response.getStatusLine().getStatusCode();

            if (code != 200) {
                System.out.println("ERROR response code : " + code);
            }

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String returnString = EntityUtils.toString(entity);
                System.out.println(returnString);

                returnDeveloperId = new Integer(this.getIntValue("providerCompanyId", returnString)).intValue();
                EntityUtils.consume(entity);
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return -1;
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
        return returnDeveloperId;
    }

    public int createUserBindThing(String thingId, String username, String password, int developerId) {
        int userId = 0;
        try {

            System.out.println("createUserBindThing(thingId: " + thingId + ", username: " + username + ", password: "
                    + password + ", developerId: " + developerId + ") ");

            CredentialsProvider provider = new BasicCredentialsProvider();
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("marktesterg@gmail.com",
                    "123456");
            provider.setCredentials(AuthScope.ANY, credentials);
            HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

            HttpPost request = new HttpPost(
                    "http://api.rapifire.com/api/v1/things/" + thingId + "/claim-and-register/");
            StringEntity params = new StringEntity("{\"username\":\"" + username + "\",\"password\":\"" + password
                    + "\",\"developerId\":\"" + developerId + "\"} ");
            request.addHeader("content-type", "application/json");
            request.addHeader("Accept", "application/json");
            request.setEntity(params);

            HttpResponse response = client.execute(request);

            int returnCode = response.getStatusLine().getStatusCode();
            if (returnCode != 200) {
                System.out.print("Error code " + returnCode);
                return -1;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String returnString = EntityUtils.toString(entity);
                userId = this.getIntValue("userId", returnString);
                EntityUtils.consume(entity);
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return -1;
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
        return userId;
    }

    public String createThing(String thingname, int productId) {
        String thingId = "";
        try {

            System.out.println("createThing(" + thingname + ", productId: " + productId + ")");

            CredentialsProvider provider = new BasicCredentialsProvider();
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("marktesterg@gmail.com",
                    "123456");
            provider.setCredentials(AuthScope.ANY, credentials);
            HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

            HttpPost request = new HttpPost("http://api.rapifire.com/api/v1/things");
            StringEntity params = new StringEntity(
                    "{\"name\":\"" + thingname + "\",\"productId\":\"" + productId + "\"} ");
            request.addHeader("content-type", "application/json");
            request.addHeader("Accept", "application/json");
            request.setEntity(params);

            HttpResponse response = client.execute(request);

            int returnCode = response.getStatusLine().getStatusCode();
            if (returnCode != 200) {
                return "ERROR " + returnCode;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String returnString = EntityUtils.toString(entity);
                thingId = this.getMsgValue("thingId", returnString);

                EntityUtils.consume(entity);
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
            thingId = "ERROR ClientProtocolException";
        } catch (IOException e) {
            e.printStackTrace();
            thingId = "ERROR IOException";
        }
        return thingId;
    }

    public int deleteThing(String thingId) {
        int returnCode = 0;
        try {

            System.out.println("deleteThing(" + thingId + ")");

            CredentialsProvider provider = new BasicCredentialsProvider();
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("marktesterg@gmail.com",
                    "123456");
            provider.setCredentials(AuthScope.ANY, credentials);
            HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

            HttpDelete request = new HttpDelete("http://api.rapifire.com/api/v1/things/" + thingId);
            HttpResponse response = client.execute(request);
            returnCode = response.getStatusLine().getStatusCode();

        } catch (ClientProtocolException e) {
            e.printStackTrace();
            returnCode = -1;
        } catch (IOException e) {
            e.printStackTrace();
            returnCode = -1;
        }
        return returnCode;
    }

    public int deleteUser(int userId) {
        int returnCode = 0;
        try {

            System.out.println("deleteUser(" + userId + ")");

            CredentialsProvider provider = new BasicCredentialsProvider();
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("marktesterg@gmail.com",
                    "123456");
            provider.setCredentials(AuthScope.ANY, credentials);
            HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

            HttpDelete request = new HttpDelete("http://api.rapifire.com/api/v1/users/" + userId);
            HttpResponse response = client.execute(request);
            returnCode = response.getStatusLine().getStatusCode();

        } catch (ClientProtocolException e) {
            e.printStackTrace();
            returnCode = -1;
        } catch (IOException e) {
            e.printStackTrace();
            returnCode = -1;
        }
        return returnCode;
    }

    public String putThingMetadata(String thingId, String key, String value) {
        String returnCode = "";
        try {

            System.out.println("putThingMetadata(" + thingId + ", key: " + key + ", value: " + value + ") ");

            CredentialsProvider provider = new BasicCredentialsProvider();
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("marktesterg@gmail.com",
                    "123456");
            provider.setCredentials(AuthScope.ANY, credentials);
            HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
            HttpPut request = new HttpPut("http://api.rapifire.com/api/v1/things/" + thingId + "/meta");
            StringEntity params = new StringEntity("{\"key\": \"" + key + "\",\"value\": \"" + value + "\"}");
            request.addHeader("content-type", "application/json");
            request.addHeader("Accept", "application/json");
            request.setEntity(params);

            HttpResponse response = client.execute(request);

            int code = response.getStatusLine().getStatusCode();
            if (code != 200) {
                returnCode = "ERROR " + code;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                EntityUtils.toString(entity);
                EntityUtils.consume(entity);
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
            returnCode = "ERROR ClientProtocolException";
        } catch (IOException e) {
            e.printStackTrace();
            returnCode = "ERROR IOException";
        }
        return returnCode;
    }

    private String getMsgValue(String name, String command) {

        int valueStart = command.indexOf(name) + name.length() + 5;
        int valueEnd = command.indexOf("\"", valueStart);
        String value = command.substring(valueStart, valueEnd);
        return value;
    }

    private int getIntValue(String name, String command) {

        int valueStart = command.indexOf(name) + name.length() + 4;
        int valueEnd = command.indexOf(",", valueStart);
        return new Integer(command.substring(valueStart, valueEnd)).intValue();
    }

    public static void main(String[] args) {

        String[] things = new String[NUM_THINGS];
        int[] users = new int[NUM_THINGS];

        AutomationApp app = new AutomationApp();

        int developerId = app.getMyDeveloperId();
        System.out.println("developerId : " + developerId + "\n");

        // Create things and assign a meta data of maximum temperature of 89.0
        // degrees C.
        for (int i = 0; i < NUM_THINGS; i++) {
            things[i] = app.createThing("Thermometer " + i, 94);
            System.out.println(" #" + i + " thingId: " + things[i]);
            app.putThingMetadata(things[i], "MaxTemp", "89.0");
            String value = app.getThingMetadataKey(things[i], "MaxTemp");
            System.out.println(" Value of MaxTemp: " + value);
        }
        System.out.println("Created with meta data " + NUM_THINGS + " things.\n");

        // Create users with username prefix "customer" and assign to a thing.
        for (int i = 0; i < NUM_THINGS; i++) {
            users[i] = app.createUserBindThing(things[i], "customer" + i, "pass123", developerId);
            System.out.println(" #" + i + " userId: " + users[i]);
        }
        System.out.println("Created & bound " + NUM_THINGS + " users.\n");

        // Delete things.
        for (int i = 0; i < NUM_THINGS; i++) {
            int httpcode = app.deleteThing(things[i]);
            System.out.println(" #" + i + " respose code: " + httpcode);
        }
        System.out.println("Deleted " + NUM_THINGS + " things.\n");

        // Delete users.
        for (int i = 0; i < NUM_USERS; i++) {
            int httpcode = app.deleteUser(users[i]);
            System.out.println(" #" + i + " respose code: " + httpcode);
        }
        System.out.println("Deleted " + NUM_USERS + " users.\n");
        System.out.println("Done");

    }

A few things to notice about the code. Let's take the createThing() method which creates a thing. First basic authorization needs to be set for the request to succeed with the developer's email address and password as below.

CredentialsProvider provider = new BasicCredentialsProvider();  
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("marktesterg@gmail.com",
                    "123456");
            provider.setCredentials(AuthScope.ANY, credentials);
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

Next the URL needs to be built according to the API specs. The headers are set for JSON content for the JSON string.

HttpPost request = new HttpPost("http://api.rapifire.com/api/v1/things");  
            StringEntity params = new StringEntity(
                    "{\"name\":\"" + thingname + "\",\"productId\":\"" + productId + "\"} ");
            request.addHeader("content-type", "application/json");
            request.addHeader("Accept", "application/json");
            request.setEntity(params);

Finally the request is executed. The HTTP status code is checked for success and the response result thingId is extracted.

                        HttpResponse response = client.execute(request);

            int returnCode = response.getStatusLine().getStatusCode();
            if (returnCode != 200) {
                return "ERROR " + returnCode;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String returnString = EntityUtils.toString(entity);
                thingId = this.getMsgValue("thingId", returnString);

                EntityUtils.consume(entity);
            }
  • Run the class and click on the Things menu. You will see Thermometer things being created and added to the dashboard.

  • Click a Thermometer thing and scroll to the bottom to view the meta data value MaxTemp set to 89.0

  • Finally the class will delete the things and users.

This concludes this example. For more information on the RAPIFIRE automation API check the Maker's Guide Automation API section.

Author image
About Mark Garzone