Monday, December 11, 2017

WebSockets and JSONDecoder in Wildfly 11


import java.io.Serializable;
import java.net.URI;

import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

import com.pierre.inst.model.Member;

@ClientEndpoint(decoders={JSONDecoder.class})
public class MemberClientEndpoint implements Serializable{

    @Inject
    private Event<Member> memberEvent;

    @OnMessage
    public void onMessage(Member member) {
        memberEvent.fire(member);
    }
}




java.lang.RuntimeException: javax.websocket.DeploymentException: UT003029: Could not find message parameter on method public void com.pierre.inst.websockets.MemberClientEndpoint.onMessage(com.pierre.inst.model.Member)

where JSONDecoder is

import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;

import com.google.gson.Gson;
import com.pierre.inst.model.Member;

public class JSONDecoder implements Decoder.Text<Object> {

 private Gson gson;

 @Override
 public void init(EndpointConfig config) {
  gson = new Gson();
 }

 @Override
 public void destroy() {
  // do nothing
 }

 @Override
 public Object decode(String s) throws DecodeException {
  return gson.fromJson(s, Member.class);
 }

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

}


see also
https://docs.oracle.com/javaee/7/tutorial/websocket007.htm
and
https://issues.jboss.org/browse/UNDERTOW-287

The issue is that JSONDecoder is too generic, parameter class is Object, it should be Member:


import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;

import com.google.gson.Gson;
import com.pierre.inst.model.Member;

public class JSONDecoder implements Decoder.Text<Member> {

 private Gson gson;

 @Override
 public void init(EndpointConfig config) {
  gson = new Gson();
 }

 @Override
 public void destroy() {
  // do nothing
 }

 @Override
 public Member decode(String s) throws DecodeException {
  return gson.fromJson(s, Member.class);
 }

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

}







No comments: