Over a million developers have joined DZone.

Reappt on Bluemix: Publish to a JSON Topic in Five Steps

Learn how to use the Reappt Java API to create a JSON topic and publish JSON values to it with the help of IBM Bluemix.

· Mobile Zone

Read our latest eBook to learn the features of JSON and why it's become dominant for web-based integration. Brought to you in partnership with Reappt.

JSON (JavaScript Object Notation) is an incredibly versatile, simple to understand, and lightweight data format. Though it has JavaScript in the name, as a text-based format, it is language independent and provides a perfect way to transmit data that has an inherent structure.

Use the Reappt Java API to create a JSON topic and publish JSON values to it.

To try this demo, you need a Reappt service. You can get a Free edition of Reappt from Bluemix. Watch a short video on how to get started with Reappt on Bluemix.

1. Download the Reappt Java Client Library and Include it in Your Java Project

Get the Reappt Java client library from our website: http://developer.reappt.io/clients/java/diffusion-client.jar. In your IDE, create a Java project and add the diffusion-client.jar file to the build path.

2. Connect to Your Reappt Service

First you need to connect to your Reappt service. You connect to your Reappt service using the URL shown on your Reappt Dashboard.

From Bluemix, click on Reappt in your list of services, then click the “OPEN REAPPT FROM PUSH TECHNOLOGY DASHBOARD” button to get to the Dashboard. Here you’ll find your service name and URL.

go_to_dashboard

On the Dashboard, you’ll also find the System Users table. To connect to your Reappt service and create topics, you’ll need a user who has the permission to create and update topics. You can create that user here. Click on the plus sign (+) to open the ‘Add Users’ wizard. In it, add a user called ‘admin’ and give the user the ‘TOPIC_CONTROL’ role.

dashboard_create_user

OK – you’re ready to connect:

Session session = Diffusion.sessions()
                    .principal("admin")
                    .password("password")
                    .open("wss://demo.reappt.io:443");


Replace ‘demo.reappt.io’ with the URL of your Reappt service and ‘password’ with the password you defined for your user ‘admin’.  The ‘wss’ prefix to the URL indicates that the client uses a secure WebSocket transport to connect to Reappt. Port 443 is the port on which Reappt accepts secure connections.

If you want to make a non-secure connection, change ‘wss’ to ‘ws’ and the port to 80. However, if you are connecting with a password, best to use a secure connection.

3. Create a JSON Topic

Next you need to create a JSON topic. To do this you can use the addTopicFromValue() method. This method uses the value you pass in to determine the type of topic you want to create. If you pass in a JSON object, Reappt will automatically create a JSON topic.

String initialValueAsString = "{ \"timestamp\":"
 + Long.toString(cal.getTimeInMillis()) + "," + "\"patients\":["
 + "{\"id\": \"0115\", \"pulse\" : 81, \"bp\" : \"127/87\" },"
 + "{\"id\": \"0121\", \"pulse\" : 68, \"bp\" : \"124/83\" },"
 + "{\"id\": \"0766\", \"pulse\" : 73, \"bp\" : \"133/89\" },"
 + "{\"id\": \"1243\", \"pulse\" : 92, \"bp\" : \"138/90\" },"
 + "{\"id\": \"1244\", \"pulse\" : 62, \"bp\" : \"119/77\" }"
 + "]" + "}";

JSON initialValueAsJson =    
    Diffusion.dataTypes().json().fromJsonString(initialValueAsString);

session.feature(TopicControl.class)
   .addTopicFromValue("topic/json", initialValueAsJson, new TopicControl.AddCallback.Default());


In this quick and dirty example code, the initial JSON value is created from a hardcoded String that matches the example output in the companion post, “Subscribe to a JSON topic in 5 steps”. The JSONDataType.fromJsonString() method converts strings of well-formed JSON into a JSON objects.

In your code, the initial JSON value would be created from your source data.

4. Register an Updater for the JSON Topic

To update a topic, you must use an updater. Get an exclusive updater by registering as an update source. Update sources are registered against branches of the topic tree and their associated updaters can only update topics that are in that branch.

JSON topics can be updated by value updaters. Value updaters are typed and only update topics that have a matching type. Using value updaters has the advantage that they cache the value of the last update. When you update with a new value, the value updater compares this value to the cached value and, if it is more efficient, sends a diff of the two values. This reduces the amount of bytes sent across the network.

To register an update source and get value updater to use to update your JSON topic, ensure that you register the update source against the topic or against a topic in its path.

session.feature(TopicUpdateControl.class).registerUpdateSource("topic",
        new UpdateSource.Default() {
            @Override
            public void onActive(String topicPath, Updater updater) {
                valueUpdater = updater.valueUpdater(JSON.class);
            }
        });


This client is registered as the exclusive update source of any topics in this branch of the topic tree. The first update source to register is the active update source and is the only update source allowed to use an updater to update the topic. If a second client attempted to register an exclusive update source against the same branch of the tree, it would become a standby source and only become active if the first update source goes away.

When the update source becomes active it provides an updater. Use the provided updater to get a value updater that is typed to JSON topics. This value updater can now be used to update any JSON topics in the ‘topic’ branch of the topic tree, for example the ‘topic/json’ topic we just created.

It is also possible to update a topic non-exclusively, if no exclusive updater is already registered for the topic.

5. Update the Topic With JSON

Use the value updater to update the topic with a JSON object:

JSON jsonData = Diffusion.dataTypes().json().fromJsonString(moreData);

valueUpdater.update(
    "topic/json",
    jsonData,
    callback);


And it’s as simple as that. You’ve just created a JSON topic and published a value to it.

You can use this example to create and update a JSON topic. To see it working, though, you need a subscriber. Check out the companion post: “Subscribe to a JSON topic in 5 steps” for a JavaScript client that subscribes to a JSON topic.

Next Steps

One of the beauties of JSON is that there are mature third-party libraries available in most languages that enable you to work easily with JSON. In Java, we recommend using Jackson.

Jackson provides a suite of data-processing tools for Java. Its core function processes data in JSON format and it provides additional module for processing data in other formats, for example CBOR. (CBOR is the data format that our JSON topics use under the covers.)

So far this example has just turned strings into JSON object, but JSON can be used to represent more complex data structures provided in Java, such as Maps.

This example method uses Jackson to turn a Map into a JSON string:

private JSON mapToJSON(Map<String, String> values) throws IOException {
    // Use the third-party Jackson library to write out the values map 
    // as a CBOR-format binary.
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final CBORGenerator generator = cborFactory.createGenerator(baos);
    generator.writeObject(values);
    return jsonDataType.readValue(baos.toByteArray());
}


Try Reappt for free at IBM Bluemix.

Read our latest eBook to learn the features of JSON and why it's become dominant for web-based integration. Brought to you in partnership with Reappt.

Topics:
MOBILE ,REAPPT ,ibm bluemix ,TOPICS ,json

Published at DZone with permission of Katherine Shann, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}