Merge branch 'cose' into 'dev'

Fixed ConcurrentModificationException on socket broadcast

See merge request sa4-2020/the-sanmarinoes/backend!65
This commit is contained in:
Claudio Maggioni 2020-03-25 23:16:14 +01:00
commit 3ccdad8202

View file

@ -1,6 +1,5 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.socket; package ch.usi.inf.sa4.sanmarinoes.smarthut.socket;
import static ch.usi.inf.sa4.sanmarinoes.smarthut.utils.Utils.didThrow;
import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonConfig; import ch.usi.inf.sa4.sanmarinoes.smarthut.config.GsonConfig;
import ch.usi.inf.sa4.sanmarinoes.smarthut.models.User; import ch.usi.inf.sa4.sanmarinoes.smarthut.models.User;
@ -8,7 +7,6 @@ import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap; import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps; import com.google.common.collect.Multimaps;
import com.google.gson.Gson; import com.google.gson.Gson;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.*;
import javax.websocket.*; import javax.websocket.*;
@ -61,28 +59,19 @@ public class SensorSocketEndpoint extends Endpoint {
*/ */
public void broadcast(Object message, User u) { public void broadcast(Object message, User u) {
final HashSet<Session> sessions = new HashSet<>(authorizedClients.get(u)); final HashSet<Session> sessions = new HashSet<>(authorizedClients.get(u));
for (Session s : sessions) {
try {
if (s.isOpen()) {
sessions.stream() s.getBasicRemote().sendText(gson.toJson(message));
.filter( } else {
s -> { authorizedClients.remove(u, s);
if (s.isOpen()) return true; }
sessions.remove(s); } catch (IOException e) {
return false; e.printStackTrace();
}) }
.forEach(s -> { }
synchronized (this){
try {
s.getBasicRemote().sendText(gson.toJson(message));
} catch (IOException e) {
e.printStackTrace();
}
}
});
} }
/** /**
* Handles the opening of a socket session with a client * Handles the opening of a socket session with a client
* *