DefaultSubscriptionRegistry and its protected methods - spring

I am trying to implement a WebSocket feature with STOMP in my SpringBoot application. So far, this is going quite alright, but I'm running into one issue.
Unsubscribing from a topic seems to always be done from the browser's side. However, using #DestinationVariable I can create a number of topics (e.g. with the path /{game_id}/chat), and I need a security feature on the server's side.
Because messages are authorized, I am able to check whether the logged user actually has access to {game_id}. If they don't, the subscription should end (not the WebSocket connection!). To do this, I autowired DefaultSubscriptionRegistry to delete the subscription from the list, but this method is apparently protected. I now find myself not knowing how to delete this subscription (which is managed by the simple broker Spring provides) from inside of Spring.
I guess another way to do this is by mocking an unsubscribe message from the browser and having the MessageHandler handle it. But that gives its own challenges, mainly obtaining the ApplicationContext of the simple broker (that I did not personally edit).
Has anyone faced this challenge before? Are there good workarounds/alternatives to unsubscribe from the server side?

Rossen has given an answer on GitHub that I believe will help with this.
Essentially, the approach is to register a ChannelInterceptor that creates a mock unsubscribe message:
#Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
StompHeaderAccessor headers =
StompHeaderAccessor.create(StompCommand.UNSUBSCRIBE);
// ... add headers
Message<?> unsubscribe = MessageBuilder
.withPayload(new byte[0]).setHeaders(headers).build();
messageHandler.handleMessage(unsubscribe);
return message;
}

Related

Redeliver message to MQ when using #JmsListener

I'm using #EnableJms and #JmsListener annotation to register a queue listener in my application, basing on this tutorial. I'm connecting to IBM MQ, getting connection factory using jndi. I have read about acknowledge modes etc. but still it's a new thing to me. And my problem is that the message is not being returned to a queue (the listener is never called again).
#Bean
public DefaultJmsListenerContainerFactory jmsListenerContainerFactory() {
DefaultJmsListenerContainerFactory factory
= new DefaultJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory());
factory.setSessionTransacted(true);
factory.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE); //I have tried also CLIENT_ACKNOWLEDGE
return factory;
}
#JmsListener(containerFactory = "jmsListenerContainerFactory", destination = "myQueue")
#SendTo("secondQueue")
public String testListener(String message){
if(true) throw new NullPointerException();
else return message;
}
Any help would be much appreciated.
I would have also a second question. From what I understand if I would like to implement any operation on a database, only way to rollback a commit (if something went wrong after this) would be to create a transaction manager? If not, I would need to detect a duplicated message.
First set the acknowledgement mode to Session.CLIENT_ACKNOWLEDGE
and when receiving the messages, if it's processed correctly then just call message.acknowledge() method or else don't call.
It will automatically stay in the queue and you don't need to resend it.
You need to use
import javax.jms.Message
I created simple Spring Boot app and Docker container of IBM MQ to test your case.
I found good instructions in this tutorial: https://developer.ibm.com/tutorials/mq-jms-application-development-with-spring-boot/
And in your case this environment behaves as expected: endless cycle of receive message -> NullPointerException -> return message -> ...
Than I found feature of IBM MQ called "Backout Queues & Thresholds", you'll found the explanation in this blog post: https://community.ibm.com/community/user/imwuc/browse/blogs/blogviewer?BlogKey=28814801-083d-4c80-be5f-90aaaf81cdfb
Briefly, it is possible to restrict number of times message returned to queue after exception, and after this limit send message to another queue.
May be in your case this feature used on your destination queue.

SpringBoot get InputStream and OutputStream from websocket

we want to integrate third party library(Eclipse XText LSP) into our SpringBoot webapp.
This library works "interactively" with the user (like chat). XText API requires input and output stream to work. We want to use WebSocket to let users interact with this library smoothly (send/retrieve json messages).
We have a problem with SpringBoot because SpringBoot support for WebSocket doesn't expose input/output streams. We wrote custom TextWebSocketHandler (subclass) but none of it's methods provide access to in/out streams.
We also tried with HandshakeInterceptor (to obtain in/out streams after handshake ) but with no success.
Can we use SpringBoot WebSocket API in this scenario or should we use some lower level (Servlet?) API ?
Regards Daniel
I am not sure if this will fit your architecture or not, but I have achieved this by using Spring Boot's STOMP support and wiring it into a custom org.eclipse.lsp4j.jsonrpc.RemoteEndpoint, rather than using a lower level API.
The approach was inspired by reading through the code provided in org.eclipse.lsp4j.launch.LSPLauncher.
JSON handler
Marhalling and unmarshalling the JSON needs to be done with the API provided with the xtext language server, rather than Jackson (which would be used by the Spring STOMP integration)
Map<String, JsonRpcMethod> supportedMethods = new LinkedHashMap<String, JsonRpcMethod>();
supportedMethods.putAll(ServiceEndpoints.getSupportedMethods(LanguageClient.class));
supportedMethods.putAll(languageServer.supportedMethods());
jsonHandler = new MessageJsonHandler(supportedMethods);
jsonHandler.setMethodProvider(remoteEndpoint);
Response / notifications
Responses and notifications are sent by a message consumer which is passed to the remoteEndpoint when constructed. The message must be marshalled by the jsonHandler so as to prevent Jackson doing it.
remoteEndpoint = new RemoteEndpoint(new MessageConsumer() {
#Override
public void consume(Message message) {
simpMessagingTemplate.convertAndSendToUser('user', '/lang/message',
jsonHandler.serialize(message));
}
}, ServiceEndpoints.toEndpoint(languageServer));
Requests
Requests can be received by using a #MessageMapping method that takes the whole #Payload as a String to avoid Jackson unmarshalling it. You can then unmarshall yourself and pass the message to the remoteEndpoint.
#MessageMapping("/lang/message")
public void incoming(#Payload String message) {
remoteEndpoint.consume(jsonHandler.parseMessage(message));
}
There may be a better way to do this, and I'll watch this question with interest, but this is an approach that I have found to work.

Spring websocket: how intercept the send event through the AbstractSubProtocolEvent hierarchy?

About Spring websocket about intercept Stomp events one approach is extends from the ChannelInterceptorAdapter class
It works how is expected. More details here:
Spring websocket: how convert easily the Message's payload to POJO in ChannelInterceptorAdapter
Now, according with this tutorial:
Detecting WebSocket Connects and Disconnects in Spring 4
the approach mentioned above is covered and other approach is work around with ApplicationEvents, it through with:
SessionConnectEvent
SessionConnectedEvent
SessionDisconnectEvent
These classes extends from:
AbstractSubProtocolEvent
And exists two subclasses more:
SessionSubscribeEvent
SessionUnsubscribeEvent
This list is confirmed in (by the same author):
how to capture connection event in my webSocket server with Spring 4?
The names are by themselves obvious to know what each one does, but just curious
Why there is no none for the send event?
It to react from:
stompClient.send('/app/ws/something',
{},
JSON.stringify({'content': $('#content').val()})
For this send event "seems" mandatory work with the ChannelInterceptorAdapter through the postSend(Message<?> message, MessageChannel channel, boolean sent) method yet
The events reflect major points in the lifecycle of a STOMP connection. They're not meant to be notifications for every message sent from the client. For that you can use #MessageMapping methods, or a ChannelInterceptor.

Dynamic provider for a Marshalling web service outbound gateway

Is it possible to set a dynamic provider for a Marshalling web service outbound gateway?
I mean, if I try for example: http://100.0.0.1 and it not works, I would like to try http://100.0.0.2 instead
My current configuration:
MarshallingWebServiceOutboundGateway gw = new MarshallingWebServiceOutboundGateway(provider, jaxb2Marshaller(), jaxb2Marshaller());
Yes, that's true. Since MarshallingWebServiceOutboundGateway allows to inject DestinationProvider, you feel free to provide any custom implementation.
For your fault-tolerant use-case you should do: new URLConnection(url).connect() to test connection to the target server in that your DestinationProvider implementation.
UPDATE
But If I how can I test new URLConnection(url).connect() if I have https credentials, certificate or any kind of security
Well, another good solution from the Spring Integration is load-balancing and several subscribers to the same DirectChannel:
#Bean
public MessageChannel wsChannel() {
return new DirectChannel(null);
}
to switch of the default RoundRobinLoadBalancingStrategy.
And after that you can have several #ServiceActivator(inputChannel="wsChannel"). When the first one is fail, the message is sent to the second and so on, until the good result or the fall for each URL.

How to stop consumers

I made a simple Jms project with 2 java files names are MessageSender.java,MessageConsumer.java.one for sending messages to Activemq:Queue and another for consuming messages from Activemq:Queue.Deployed this project in Apache Tomcat.following code was consumer code.
ActiveMQConnectionFactory connectionFactory=new ActiveMQConnectionFactory("admin","admin","tcp://localhost:61617?jms.prefetchPolicy.queuePrefetch=1");
Connection connection=connectionFactory.createConnection();
final Session session=connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
Queue queue=session.createQueue("ThermalMap");
javax.jms.MessageConsumer consumer=session.createConsumer(queue);
//anonymous class
MessageListener listener = new MessageListener() {
#Override
public void onMessage(Message msg) {
// My business code
}
};
Later If I want to change consumer code,I don't want to stop Tomcatbecause If I stop Tomcat entire jms project should not work. So clients can't able to sent messages to Activemq:Queue.So I don't want to follow this way.
I am thinking, If I stop consumers through Activemq console page.I don't need to stop Tomcat So clients can able to send messages normally.For this I check AMQ console page,I didn't seen any consumers.
Is it correct way to do this.
If it is correct way, How can I do this.
can anyone suggest me.
Thanks.
Call the .close() method on your MessageConsumer.

Resources