Fabrizio
Fabrizio

Reputation: 73

Wait for Response on REST Request JAVA

I created a java project with glassfish and posted a simple REST GET service like this:

@Path("/get") 
public class Rest {
     @Path("test/{user}/")
     @GET
     public String getTest(@PathParam("user") String id) throws IOException {
        //send message to websocket client and wait for response

         //return "websocket client response";
     }
}

this works fine.

I also have a websocket server implementation in the same project. This implementation allows me to send data to the connected clients.

This is my WebSocket implementation:

@ServerEndpoint("/websocket")
public class WebSocketServer {


    @OnOpen
    public void onOpen(Session userSession){
        System.out.println("Se conecto un nuevo cliente");

        Modelo.getInstance().users.add(userSession);

    }
    @OnMessage
    public void onMessage(String message,Session userSession) throws IOException{
        String username=(String) userSession.getUserProperties().get("username");

        if(username==null){
            userSession.getUserProperties().put("username", message);
            userSession.getBasicRemote().sendText(Modelo.getInstance().buildJsonData("Servidor","nuevo cliente conectado como: "+message));

        }else{
            Iterator<Session> iterator=Modelo.getInstance().users.iterator();
            while(iterator.hasNext()){
                iterator.next().getBasicRemote().sendText(Modelo.getInstance().buildJsonData(username,message));
            }
        }
    }
    @OnClose
    public void onClose(Session userSession){
        Modelo.getInstance().users.remove(userSession);

    }
    @OnError
    public void onError(Throwable t){
        t.printStackTrace();
    }
}

this works fine too.

When the REST method is called i can send successfully a message to one of my websockets clients.

The thing is that i want to return as the REST response, the data that the WebSocket client sends me.

So... 1)Receive REST GET request in Java Server 2)Send via websocket to the client i want to get the info from 3)Respond the REST GET request with the message the websocket client send me.

How can i accomplish this?

[SOLVED]?

I found a way to do this, please i would like to know what do you think.

I found this article: here about async rest reponses.

So i implemented, its the first thing come to my mind, i save the websocket client message in an array, and the REST request is responded when the array has a message.

@Path("/resource")
     @GET
     public void asyncGet(@Suspended final AsyncResponse asyncResponse) throws IOException {
         Modelo.getInstance().enviarMensaje("5", "escenas");

         new Thread(new Runnable() {
             @Override
             public void run() {
                 String result = veryExpensiveOperation();
                 asyncResponse.resume(result);
             }

             private String veryExpensiveOperation() {
                while(Modelo.getInstance().responses.size()==0){

                }
                String result=Modelo.getInstance().responses.get(0);
                Modelo.getInstance().responses.clear();
                return result;
                 // ... very expensive operation
             }
         }).start();
     }

I know there a more things to validate this reponses, but at first it works.

I also edit the websockerserver.java to save in the array the response.

Thank you very much

Upvotes: 1

Views: 7284

Answers (1)

Bob Paulin
Bob Paulin

Reputation: 1118

REST works over HTTP which is a request/response model of communication. Which means you need to send a request in order to get a response. Web Sockets is a full duplex socket model. This means the client or the server can send a message as long as the connection is up. The challenge is you're trying to send a response with REST without a request. You could queue the response from the web socket and then send it back with the next REST response. This would however require the REST client to poll the server periodically since you would not have an indication of when the Web Socket client responded.

Upvotes: 1

Related Questions