How can I send rest request to socket - java

I tried to create an API that send request via socket.
Code:
#Controller
public class GreetingController {
#GetMapping("/x")
public void send() {
greeting(new HelloMessage("Admin", "bla"));
}
#MessageMapping("/hello")
#SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) {
return new Greeting(HtmlUtils.htmlEscape(message.getName() + ": " + message.getMsg()));
}
}
I don't understand how to send request via rest to websocket.
Can anyone explain why when I send a request to /x the websocket does not get new HelloMessage?

When you call another method from the same class, you just do that: call a method. This method call doesn't care whether the called method has annotations.
The greeting() method only sends a message when it's called from a websocket client posting a message to /hello.
To send a message programmatically, you use the SimpMessageTemplate, as documented:
What if you want to send messages to connected clients from any part of the application? Any application component can send messages to the brokerChannel. The easiest way to do so is to inject a SimpMessagingTemplate and use it to send messages. Typically, you would inject it by type, as the following example shows:
#Controller
public class GreetingController {
private SimpMessagingTemplate template;
#Autowired
public GreetingController(SimpMessagingTemplate template) {
this.template = template;
}
#RequestMapping(path="/greetings", method=POST)
public void greet(String greeting) {
String text = "[" + getTimestamp() + "]:" + greeting;
this.template.convertAndSend("/topic/greetings", text);
}
}

Related

StompSessionHandler not calling handleFrame in afterConnected block?

I have a fairly simple setup to test Stomp support in Spring.
I was planning on using JS to send messages to the queue and receive and handle them in Spring app. However, it doesn't seem to work for some reason.
JS client:
var ws = new SockJS('/hello');
client = Stomp.over(ws);
...
client.subscribe('jms.queue.test', function(message) {}
...
client.send("jms.queue.test", {}, "message");
Spring config (mostly useless at the moment, since i don't use /app destination):
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableStompBrokerRelay("jms.topic", "jms.queue");
config.setApplicationDestinationPrefixes("/app");
config.setPathMatcher(new AntPathMatcher("."));
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/hello").withSockJS();
}
}
Spring Boot App:
#Component
public class BusinessLogic implements CommandLineRunner {
#Autowired
hulloController controller;
#Override
public void run(String... args) throws Exception {
stuff(args);
}
public void stuff(String[] args) throws InterruptedException {
Thread.sleep(20000);//sleep while spring boot fully initializes
controller.waitForGreet();
}
}
Controller (not a real #Controller, i don't plan to use MVC):
#Component
public class hulloController {
private SimpMessagingTemplate template;
#Autowired
StompSessionHandler handler;
#Autowired
public hulloController(SimpMessagingTemplate template) {
this.template = template;
}
public void waitForGreet() {
System.out.println("Entered Listener");
WebSocketClient transport = new StandardWebSocketClient();
WebSocketStompClient stompClient = new WebSocketStompClient(transport);
stompClient.setMessageConverter(new StringMessageConverter());
stompClient.connect("ws://127.0.0.1:61613/stomp", handler);
}
}
And finally, the handler:
#Component
public class SessionHandler implements StompSessionHandler {
#Override
public void afterConnected(StompSession stompSession, StompHeaders stompHeaders) {
System.out.println("Connected!");
StompFrameHandler handler = new StompFrameHandler() {
#Override
public Type getPayloadType(StompHeaders stompHeaders) {
return null;
}
#Override
public void handleFrame(StompHeaders stompHeaders, Object o) {
System.out.println("received " + o.toString());
}
};
//StompSession.Subscription s = stompSession.subscribe("jms.queue.test", handler);
stompSession.send("jms.queue.test", "hello!");
}
...
}
If i comment the client.subscribe part, client.send works properly, message is received and rendered in JS, so the queue names and connection URL are fine. I also tried using SockJSClient as a Transport but it doesn't help.
When i send messages from JS, for about 1 or 2 minutes half of them isn't showing up (as it would be if the subscription would be working), then JS starts receiving 100% of the messages.
I've seen plenty of almost identical code on github today, and i just don't see what the issue might be here.
//StompSession.Subscription s = stompSession.subscribe("jms.queue.test", handler);
stompSession.send("jms.queue.test", "hello!");
The STOMP over WebSocket is a an async protocol.
You call there subscribe and got to the send. There is no guaranty that the subscription will happen already, when you start to send something to that destination.
Consider to use StompSession.Subscription and its addReceiptTask() to send messages to the destination after the confirmation for the subscription.
And you should enable StompSession.setAutoReceipt(true) to make that working with your STOMP Broker.
So, apparently switching from implementing StompSessionHandler to extending StompSessionHandlerAdapter for my handler did the trick.
I have absolutely no idea why, but i guess this passage from Spring docs for StompSessionHandler is there for a reason:
"Implementations of this interface should consider extending
StompSessionHandlerAdapter."
#Override
public Type getPayloadType(StompHeaders stompHeaders) {
return null;
}
because of this line: you supply unhandled converter - it throws exception. But it's not logged or anything. check out the code and paste proper Type instead of null

Spring Stomp CAN send unsolicited messages

In the Spring WebSocket docs I found this sentence:
It is important to know that a server cannot send unsolicited messages.
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html
(25.4.1)
However I tried this code:
#Controller
public class WebsocketTest {
#Autowired
public SimpMessageSendingOperations messagingTemplate;
#PostConstruct
public void init(){
ScheduledExecutorService statusTimerExecutor=Executors.newSingleThreadScheduledExecutor();
statusTimerExecutor.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
messagingTemplate.convertAndSend("/topic/greetings", new Object());
}
}, 5000,5000, TimeUnit.MILLISECONDS);
}
}
And the message is broadcasted every 5000ms as expected.
So why Spring docs says that a server cannot send unsollicited messages?
The next sentence might mean that in the stomp.js client you are required to set a subscription:
All messages from a server must be in response to a specific client
subscription
But this does not necessarily mean in response to a request. For example a web socket could send information to the following:
Javascript:
stompClient.subscribe('/return/analyze', function(data) {
generateTableData(JSON.parse(data.body));
});
Spring:
#Autowired
private SimpMessagingTemplate simpMessagingTemplate;
public void sendSetpoint(String data) throws Exception {
this.simpMessagingTemplate.convertAndSend("/return/analyze", data);
}
But it cannot send unsolicited messages to the client unless that subscription exists. If this is their intended point it is a little poorly worded.

Replying multiple times over web-socket without spring authentication

Note: see update at the bottom of the question for what I eventually concluded.
I need to send multiple responses to a request over the web socket that sent the request message, the first one quickly, and the others after the data is verified (somewhere between 10 and 60 seconds later, from multiple parallel threads).
I am having trouble getting the later responses to stop broadcasting over all open web sockets. How do I get them to only send to the initial web socket? Or should I use something besides Spring STOMP (because, to be honest, all I want is the message routing to various functions, I don't need or want the ability to broadcast to other web sockets, so I suspect I could write the message distributor myself, even though it is reinventing the wheel).
I am not using Spring Authentication (this is being retrofitted into legacy code).
On the initial return message, I can use #SendToUser, and even though we don't have a user, Spring only sends the return value to the websocket that sent the message. (see this question).
With the slower responses, though, I think I need to use SimpMessagingTemplate.convertAndSendToUser(user, destination, message), but I can't, because I have to pass in the user, and I can't figure out what user the #SendToUser used. I tried to follow the steps in this question, but didn't get it to work when not authenticated (principal.getName() returns null in this case).
I've simplified this considerably for the prototype, so don't worry about synchronizing threads or anything. I just want the web sockets to work correctly.
Here is my controller:
#Controller
public class TestSocketController
{
private SimpMessagingTemplate template;
#Autowired
public TestSocketController(SimpMessagingTemplate template)
{
this.template = template;
}
// This doesn't work because I need to pass something for the first parameter.
// If I just use convertAndSend, it broacasts the response to all browsers
void setResults(String ret)
{
template.convertAndSendToUser("", "/user/topic/testwsresponse", ret);
}
// this only sends "Testing Return" to the browser tab hooked to this websocket
#MessageMapping(value="/testws")
#SendToUser("/topic/testwsresponse")
public String handleTestWS(String msg) throws InterruptedException
{
(new Thread(new Later(this))).start();
return "Testing Return";
}
public class Later implements Runnable
{
TestSocketController Controller;
public Later(TestSocketController controller)
{
Controller = controller;
}
public void run()
{
try
{
java.lang.Thread.sleep(2000);
Controller.setResults("Testing Later Return");
}
catch (Exception e)
{
}
}
}
}
For the record, here is the browser side:
var client = null;
function sendMessage()
{
client.send('/app/testws', {}, 'Test');
}
// hooked to a button
function test()
{
if (client != null)
{
sendMessage();
return;
}
var socket = new SockJS('/application-name/sendws/');
client = Stomp.over(socket);
client.connect({}, function(frame)
{
client.subscribe('/user/topic/testwsresponse', function(message)
{
alert(message);
});
sendMessage();
});
});
And here is the config:
#Configuration
#EnableWebSocketMessageBroker
public class TestSocketConfig extends AbstractWebSocketMessageBrokerConfigurer
{
#Override
public void configureMessageBroker(MessageBrokerRegistry config)
{
config.setApplicationDestinationPrefixes("/app");
config.enableSimpleBroker("/queue", "/topic");
config.setUserDestinationPrefix("/user");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry)
{
registry.addEndpoint("/sendws").withSockJS();
}
}
UPDATE: Due to the security issues involved with the possibility of information being sent over other websockets than the originating socket, I ended up recommending to my group that we do not use the Spring 4.0 implementation of STOMP over Web Sockets. I understand why the Spring team did it the way they did it, and it is more power then we needed, but the security restrictions on our project were severe enough, and the actual requirements were simple enough, that we decided to go a different way. That doesn't invalidate the answers below, so make your own decision based on your projects needs. At least we have hopefully all learned the limitations of the technology, for good or bad.
Why don't you use a separate topic for each client?
Client generates a session id.
var sessionId = Math.random().toString(36).substring(7);
Client subscribes to /topic/testwsresponse/{sessionId}, then sends a message to '/app/testws/{sessionId}'.
In your controller you use #MessageMapping(value="/testws/{sessionId}") and remove #SendToUser. You can use #DestinationVariable to access sessionId in your method.
The controller sends further responses to /topic/testwsresponse/{sessionId}.
Essentially Spring does a similar thing internally when you use user destinations. Since you don't use Spring Authentication you cannot rely on this mechanism but you can easily implement your own as I described above.
var client = null;
var sessionId = Math.random().toString(36).substring(7);
function sendMessage()
{
client.send('/app/testws/' + sessionId, {}, 'Test');
}
// hooked to a button
function test()
{
if (client != null)
{
sendMessage();
return;
}
var socket = new SockJS('/application-name/sendws/');
client = Stomp.over(socket);
client.connect({}, function(frame)
{
client.subscribe('/topic/testwsresponse/' + sessionId, function(message)
{
alert(message);
});
// Need to wait until subscription is complete
setTimeout(sendMessage, 1000);
});
});
Controller:
#Controller
public class TestSocketController
{
private SimpMessagingTemplate template;
#Autowired
public TestSocketController(SimpMessagingTemplate template)
{
this.template = template;
}
void setResults(String ret, String sessionId)
{
template.convertAndSend("/topic/testwsresponse/" + sessionId, ret);
}
#MessageMapping(value="/testws/{sessionId}")
public void handleTestWS(#DestinationVariable String sessionId, #Payload String msg) throws InterruptedException
{
(new Thread(new Later(this, sessionId))).start();
setResults("Testing Return", sessionId);
}
public class Later implements Runnable
{
TestSocketController Controller;
String sessionId;
public Later(TestSocketController controller, String sessionId)
{
Controller = controller;
this.sessionId = sessionId;
}
public void run()
{
try
{
java.lang.Thread.sleep(2000);
Controller.setResults("Testing Later Return", sessionId);
}
catch (Exception e)
{
}
}
}
}
Just tested it, works as expected.
This is not full answer. Just general consideration and suggestion.
You cannot do different stuff or type of connection via the same socket. Why not have different sockets for different work? Some with authentication and some without. Some for quick task and some for long execution.

how to capture subscribe event in my webSocket server with Spring 4

I did a simple web socket communication with spring 4, STOMP and sock.js, following this https://spring.io/guides/gs/messaging-stomp-websocket/
Now I want to upgrade it to simple chat. My problem is that when user subscribes to new chat room, he should get past messages. I don't know how to capture the moment when he subscribed to send him the list of the messages.
I tried using #MessageMapping annotation, but didn't reach any success:
#Controller
public class WebSocketController {
#Autowired
private SimpMessagingTemplate messagingTemplate;
#MessageMapping("/chat/{chatId}")
public void chat(ChatMessage message, #DestinationVariable String chatId) {
messagingTemplate.convertAndSend("/chat/" + chatId, new ChatMessage("message: " + message.getText()));
}
#SubscribeMapping("/chat")
public void chatInit() {
System.out.println("worked");
int chatId = 1; //for example
messagingTemplate.convertAndSend("/chat/" + chatId, new ChatMessage("connected"));
}
}
Then I created that:
#Controller
public class ApplicationEventObserverController implements ApplicationListener<ApplicationEvent> {
#Override
public void onApplicationEvent(ApplicationEvent applicationEvent) {
System.out.println(applicationEvent);
}
}
It works, but captures all possible events, I don't think it is a good practice.
So, my question can be rephrased: how to send initial data when user subscried to sth?
You can return anything directly to a client when it subscribes to a destination using a #SubscribeMapping handler method. The returned object won't go to the broker but will be sent directly to the client:
#SubscribeMapping("/chat")
public Collection<ChatMessage> chatInit() {
...
return messages;
}
On the client side:
socket.subscribe("/app/chat", function(message) {
...
});
Check out the chat example on GitHub, which shows this exact scenario.

Push message from Java with Spring 4 WebSocket

I'd like to push messages from Java to WebSocket clients. I've successfully made a js client send to the server and receive a message back on 2 js clients, so the client side code works fine.
My issue is that I'd like to initiate a send when events occur within the Java app. So for example every time 10 orders have been placed send a message to all subscribed clients. Is this possible?
My current config:
<websocket:message-broker application-destination-prefix="/app">
<websocket:stomp-endpoint path="/hello">
<websocket:sockjs/>
</websocket:stomp-endpoint>
<websocket:simple-broker prefix="/topic"/>
</websocket:message-broker>
#Controller
public class MessageController {
#MessageMapping("/hello")
#SendTo("/topic/greetings")
public Greeting greeting() throws Exception {
return new Greeting("Hello world");
}
}
What I'd like to be able to do is something like this:
public class OrderManager {
#Autowired MessageController messageController;
int orderCount = 0;
public void processOrder(Order o) {
orderCount++;
if(orderCount % 10 == 0)
messageController.greeting();
}
}
and all subscribed clients to the websocket receive a message.
You can use the SimpMessagingTemplate. It's automatically registered. Just autowire it in any Spring bean you want.
#Autowired
private SimpMessagingTemplate template;
...
this.template.convertAndSend("/topic/greetings", text);

Categories