Coverage Summary for Class: Chat (it.polimi.ingsw.view.socket)

Class Method, % Line, %
Chat 0% (0/ 5) 0% (0/ 22)
Chat$1 0% (0/ 1) 0% (0/ 1)
total 0% (0/ 6) 0% (0/ 23)


1 package it.polimi.ingsw.view.socket; 2  3 import java.util.ArrayList; 4  5 import com.google.gson.Gson; 6 import com.google.gson.JsonSyntaxException; 7 import com.google.gson.reflect.TypeToken; 8  9 import it.polimi.ingsw.utils.Observable; 10 import it.polimi.ingsw.utils.Observer; 11 import it.polimi.ingsw.utils.model.ChatMessage; 12  13 /** 14  * Client Chat Manager 15  */ 16 public class Chat extends Observable<ChatMessage> implements Observer<String> { 17  /** 18  * Chat History 19  */ 20  private ArrayList<ChatMessage> chatHistory = new ArrayList<>(); 21  /** 22  * Socket Connection 23  */ 24  private final Connection connection; 25  /** 26  * History limit 27  */ 28  final private int limit = 50; 29  30  /** 31  * Chat constructor 32  * 33  * @param connection socket connection 34  */ 35  public Chat(Connection connection) { 36  this.connection = connection; 37  connection.addObservers(this); 38  } 39  40  /** 41  * Add a new message to history 42  * 43  * @param message message to add 44  */ 45  private synchronized void addMessage(ChatMessage message) { 46  chatHistory.add(message); 47  if (chatHistory.size() > limit) 48  chatHistory.remove(0); 49  } 50  51  /** 52  * Get Chat History 53  * 54  * @return chat history 55  */ 56  public ArrayList<ChatMessage> getHistory() { 57  return new Gson().fromJson(new Gson().toJson(chatHistory), new TypeToken<ArrayList<ChatMessage>>() { 58  }.getType()); 59  } 60  61  /** 62  * Send a message 63  * 64  * @param message message to send 65  */ 66  public void sendMessage(String message) { 67  connection.send(new Gson().toJson(new ChatMessage(null, message))); 68  } 69  70  /** 71  * Listen on new message coming from socket 72  */ 73  @Override 74  public void update(String message) { 75  try { 76  ChatMessage parsed = new Gson().fromJson(message, ChatMessage.class); 77  if (parsed == null || parsed.getUsername() == null || parsed.getMessage() == null) 78  return; 79  addMessage(parsed); 80  notify(parsed); 81  } catch (JsonSyntaxException e) { 82  // Fail Json Convert 83  } 84  } 85 }