Skip to content

Integration guide for streams

silvinci edited this page Jul 13, 2012 · 2 revisions

Xon's HeroicDeathtoJSONAPI plugin is a great example of how to take events and forward them on to JSONAPI.

You can find HeroicDeathtoJSONAPI at https://github.com/Xon/HeroicDeathToJSONAPI/ .

#Some pointers You need to add JSONAPI.jar to your classpath when compiling. In Eclipse, this means adding JSONAPI.jar to the build path.

Essentially, you just need to check that JSONAPI is loaded by running some code like this:

private JSONAPI jsonapi;
...
Plugin checkplugin = this.getServer().getPluginManager().getPlugin("JSONAPI");
if(checkplugin != null) {
    // get the JSONAPI instance
    jsonapi = (JSONAPI)checkplugin;
}
else {
    // JSONAPI isn't loaded. Throw an error or continue on your way.
}

You now need to make 2 classes: one to represent your new stream and one to represent each message in the stream:

class SampleStream extends JSONAPIStream {
    public SampleStream(String name) {
        super(name);
    }
}

class SampleMessage extends JSONAPIStreamMessage {
    String hold;
    public SampleMessage(String m) {
        hold = m;
    }

    public streamName() {
        return "sample";
    }
    
    public toJSONObject() {
        // important: make sure you import org.json.simpleForBukkit.JSONObject not import org.json.simple.JSONObject.
        JSONObject o = new JSONObject(); 
        o.put("time", getTime());
        o.put("message", hold);
        return o;
    }
}

With these objects you just need to register your stream:

JSONAPIStream sampleStream = new SampleStream();
jsonapi.getStreamManager().registerStream("sample", sampleStream);

You can now push messages to the stream and anyone who is subscribed to the stream will receive them:

sampleStream.addMessage(new SampleMessage("hi!"));