I have updated my Play Framework version from 2.4.1 to 2.5.6 but now I have a problem with the web sockets management.
I have a Controller class where method liveUpdate()
return a WebSocket<String>
instance.
In this method I use WebSocket.whenReady()
using Out<String>
in a HashMap<Out<String>, String>
where the key is the client output stream and the value is a String
that contains the language information because when I need to send a broadcast message I iterate the HashMap
.
Now all this is removed or deprecated in 2.5.6!
Searching the web I found that the new implementation is based on Akka Streams using the Flow
class but I have no idea how to adapt my code.
WebSocket.whenReady()
is replaced byWebSocket.Text.accept()
Out<?>
is replaced by akka stream withFlow
class
This is my code:
Alarms.java
public class Alarms extends Controller {
@Inject
private ActiveAlarms activeAlarms;
[...]
public WebSocket liveUpdate() {
return WebSocket.whenReady((in, out) -> {
in.onMessage(language ->{
activeAlarms.register(out, language);
});
in.onClose(() -> activeAlarms.unregister(out));
});
}
[...]
}
ActiveAlarms.java
public class ActiveAlarms{
private HashMap<Out<String>, String> websockets = new HashMap<>();
[...]
public void register(Out<String> out, String language) {
websockets.put(out, language);
updateWebsockets(out, language);
}
public void unregister(Out<String> out) {
websockets.remove(out);
}
private void updateWebsockets(Out<String> s, String lang){
if(s == null) return;
List<AlarmEvent> alarmsList = AlarmEvent.findActive();
ArrayList<AlarmEvent> translatedAlarmsList = new ArrayList<>();
//translate
alarmsList.forEach(e ->{
if(e != null) {
e.setAlarm(e.getAlarm().translate(checkLanguage(lang)));
translatedAlarmsList.add(e);
}
});
//WRITE TO SOCKET
String alarms = Json.stringify(Json.toJson(translatedAlarmsList));
try {
s.write(alarms);
} catch (Exception e2) {
Logger.debug("EX ActiveAlarms --> updateWebSocket " + e2.getMessage());
}
}
private void updateWebsockets(){
websockets.forEach(this::updateWebsockets);
}
[...]
}
Any idea on how to convert my code to the new implementation of WebSocket
?