How to Receive a Message from OpenStack Zaqar with the Java API for WebSocket

JsonDecoder.java

import java.io.StringReader;

import javax.json.Json;
import javax.json.JsonObject;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;

public final class JsonDecoder implements Decoder.Text<JsonObject> {

  @Override
  public JsonObject decode(final String s) {
    return Json.createReader(new StringReader(s)).readObject();
  }

  @Override
  public void destroy() {
  }

  @Override
  public void init(final EndpointConfig config) {
  }

  @Override
  public boolean willDecode(final String s) {
    return true;
  }

}

SampleZaqarEndpoint.java

import static java.lang.System.out;

import java.io.IOException;

import javax.json.JsonObject;
import javax.websocket.ClientEndpoint;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;

@ClientEndpoint(decoders = JsonDecoder.class)
public final class SampleZaqarEndpoint {

  @OnMessage
  public void onMessage(final JsonObject msg) {

    if (msg.getJsonObject("body").getJsonArray("messages") != null)
      out.println(msg.getJsonObject("body").getJsonArray("messages").getJsonObject(0).getString("body"));

  }

  @OnOpen
  public void onOpen(final Session sess) throws IOException {
    final RemoteEndpoint.Basic remote = sess.getBasicRemote();

    remote.sendText("{\"action\":\"authenticate\",\"headers\":{\"X-Auth-Token\":...,\"X-Project-ID\":...}}"); // refer to bug #1553398

    remote.sendText("{\"action\":\"claim_create\",\"body\":{\"queue_name\":\"SampleQueue\"},\"headers\":{\"Client-ID\":...,\"X-Project-ID\":...}}");
  }

}

SampleZaqarServlet.java

import java.net.URI;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.ContainerProvider;
import javax.websocket.WebSocketContainer;

@SuppressWarnings("serial")
@WebServlet(name = "SampleZaqarServlet", value = "/")
public final class SampleZaqarServlet extends HttpServlet {

  @Override
  protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) {
    final WebSocketContainer container = ContainerProvider.getWebSocketContainer();

    container.connectToServer(SampleZaqarEndpoint.class, new URI("ws://host:9090"));
  }

}

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