* Calculates the connectionState resulting from the message in the current connection state.
  * Checks if the specified message is allowed in the connection's state and throws an exception if
  * not.
  * @param con
  * @param msg
  * @return
  * @throws won.protocol.exception.IllegalMessageForConnectionStateException if the message is not
  *     allowed in the connection's current state
 private ConnectionState performStateTransit(Connection con, ConnectionEventType msg)
     throws IllegalMessageForConnectionStateException {
   if (!msg.isMessageAllowed(con.getState())) {
     throw new IllegalMessageForConnectionStateException(
         con.getConnectionURI(), msg.name(), con.getState());
   return con.getState().transit(msg);
  public Connection saveChatMessage(Connection con, String message)
      throws NoSuchConnectionException { // load connection, checking if it exists
    if (con == null) throw new IllegalArgumentException("connectionURI is not set");
    if (message == null) throw new IllegalArgumentException("message is not set");

    // construct chatMessage object to store in the db
    ChatMessage chatMessage = new ChatMessage();
    chatMessage.setCreationDate(new Date());
    // save in the db

    return con;
  public Connection getConnection(
      List<Connection> connections, URI facetURI, ConnectionEventType eventType)
      throws ConnectionAlreadyExistsException {
    Connection con = null;

    for (Connection c : connections) {
      // TODO: check remote need type as well or create GroupMemberFacet
      if (facetURI.equals(c.getTypeURI())) con = c;

     * check if there already exists a connection between those two we have multiple options: a) no
     * connection exists -> create new b) a connection exists in state CONNECTED -> error message c)
     * a connection exists in state REQUEST_SENT. The call must be a duplicate (or re-sent after the
     * remote end hasn't replied for some time) -> error message d) a connection exists in state
     * REQUEST_RECEIVED. The remote end tried to connect before we did. -> error message e) a
     * connection exists in state CLOSED -> create new

    // TODO: impose unique constraint on connections
    if (con != null) {
      if (con.getState() == ConnectionState.CONNECTED
          || con.getState() == ConnectionState.REQUEST_SENT)
        throw new ConnectionAlreadyExistsException(
            con.getConnectionURI(), con.getNeedURI(), con.getRemoteNeedURI());
        throw new ConnectionAlreadyExistsException(con.getConnectionURI(), con.getNeedURI(), con.getRemoteNeedURI());
      }*/ else {
        // TODO: Move this to the transition() - Method in ConnectionState
        con = connectionRepository.saveAndFlush(con);

    return con;