private void handleDisconnect() {
   Connection c = null;
   try {
     netCode = ois.readInt();
     c = checkConnectionNetCode();
     if (c != null && c.getState() == Connection.STATE_CONNECTED) {
       oos.writeInt(DISCONNECTED);
       oos.flush();
       System.out.println("->DISCONNECTED"); // $NON-NLS-1$
       c.setState(Connection.STATE_DISCONNECTED);
     } else {
       System.out.println("->NOT_CONNECTED"); // $NON-NLS-1$
       oos.writeInt(NOT_CONNECTED);
       oos.flush();
     }
   } catch (IOException e) {
     System.out.println("handleDisconnect: " + e.getMessage()); // $NON-NLS-1$
     if (c != null) {
       c.setState(Connection.STATE_DISCONNECTED);
       System.out.println(
           "Connection closed with "
               + //$NON-NLS-1$
               c.getRemoteAddress()
               + ":"
               + c.getRemotePort()); // $NON-NLS-1$
     }
   }
 }
  private void handleSendCode() {
    Connection c = null;
    GeneticCode code;

    try {
      netCode = ois.readInt();
      c = checkConnectionNetCode();
      if (c != null && c.getState() == Connection.STATE_CONNECTED) {
        oos.writeInt(WAITING_CODE);
        oos.flush();
        System.out.println("->WAITING_CODE"); // $NON-NLS-1$
        code = (GeneticCode) ois.readObject();
        System.out.println("Genetic code"); // $NON-NLS-1$
        oos.writeInt(CODE_RECEIVED);
        oos.flush();
        System.out.println("->CODE_RECEIVED"); // $NON-NLS-1$
        c.getInCorridor().receiveOrganism(code);
      } else {
        System.out.println("->NOT_CONNECTED"); // $NON-NLS-1$
        oos.writeInt(NOT_CONNECTED);
        oos.flush();
      }
    } catch (IOException e) {
      System.out.println("handleSendCode: " + e.getMessage()); // $NON-NLS-1$
      if (c != null) {
        c.setState(Connection.STATE_DISCONNECTED);
        System.out.println(
            "Connection closed with "
                + c.getRemoteAddress()
                + //$NON-NLS-1$
                ":"
                + c.getRemotePort()); // $NON-NLS-1$
      }
    } catch (ClassNotFoundException e) {
      System.out.println("handleSendCode: " + e.getMessage()); // $NON-NLS-1$
      if (c != null) {
        c.setState(Connection.STATE_DISCONNECTED);
        System.out.println(
            "Connection closed with "
                + c.getRemoteAddress()
                + //$NON-NLS-1$
                ":"
                + c.getRemotePort()); // $NON-NLS-1$
      }
    }
  }
 public void closeServer() {
   isActive = false;
   // Remove all connections
   synchronized (connections) {
     for (Connection c : connections) {
       c.send(DISCONNECT);
       c.setState(DISCONNECTED);
     }
   }
   connections = Collections.synchronizedList(new ArrayList<Connection>());
 }
 @SuppressWarnings("unchecked")
 @Override
 public void onConnected(Connection con) throws IOException {
   con.setState(Connection.State.connecting);
   String info =
       con.getDirection() == Connection.Direction.in
           ? "remote peer connected to me " + con
           : " connected to remote peer " + con;
   LOGGER.info(info);
   handler.onConnected(con);
 }
 public Connection nextConnectionState(URI connectionURI, ConnectionEventType connectionEventType)
     throws NoSuchConnectionException, IllegalMessageForConnectionStateException {
   if (connectionURI == null) throw new IllegalArgumentException("connectionURI is not set");
   // load connection, checking if it exists
   Connection con = DataAccessUtils.loadConnection(connectionRepository, connectionURI);
   // perform state transit
   ConnectionState nextState = performStateTransit(con, connectionEventType);
   // set new state and save in the db
   con.setState(nextState);
   // save in the db
   return connectionRepository.saveAndFlush(con);
 }
  /**
   * Creates a new Connection object. Expects <> won:hasFacet [FACET] in the RDF content, will throw
   * exception if it's not there.
   *
   * @param needURI
   * @param otherNeedURI
   * @param otherConnectionURI
   * @param content
   * @param connectionState
   * @param connectionEventType
   * @return
   * @throws NoSuchNeedException
   * @throws IllegalMessageForNeedStateException
   * @throws ConnectionAlreadyExistsException
   */
  public Connection createConnection(
      final URI needURI,
      final URI otherNeedURI,
      final URI otherConnectionURI,
      final Model content,
      final ConnectionState connectionState,
      final ConnectionEventType connectionEventType)
      throws NoSuchNeedException, IllegalMessageForNeedStateException,
          ConnectionAlreadyExistsException {

    if (needURI == null) throw new IllegalArgumentException("needURI is not set");
    if (otherNeedURI == null) throw new IllegalArgumentException("otherNeedURI is not set");
    if (needURI.equals(otherNeedURI))
      throw new IllegalArgumentException("needURI and otherNeedURI are the same");

    // Load need (throws exception if not found)
    Need need = DataAccessUtils.loadNeed(needRepository, needURI);
    if (!isNeedActive(need))
      throw new IllegalMessageForNeedStateException(
          needURI, connectionEventType.name(), need.getState());

    URI facetURI = getFacet(content);
    if (facetURI == null)
      throw new IllegalArgumentException(
          "at least one RDF node must be of type won:" + WON.HAS_FACET.getLocalName());
    // TODO: create a proper exception if a facet is not supported by a need
    if (facetRepository.findByNeedURIAndTypeURI(needURI, facetURI).isEmpty())
      throw new RuntimeException("Facet is not supported by Need: " + facetURI);

    List<Connection> connections =
        connectionRepository.findByNeedURIAndRemoteNeedURI(needURI, otherNeedURI);
    Connection con = getConnection(connections, facetURI, connectionEventType);

    if (con == null) {
      /* Create connection */
      con = new Connection();
      con.setNeedURI(needURI);
      con.setState(connectionState);
      con.setRemoteNeedURI(otherNeedURI);
      con.setRemoteConnectionURI(otherConnectionURI);
      con.setTypeURI(facetURI);
      // save connection (this creates a new id)
      con = connectionRepository.saveAndFlush(con);
      // create and set new uri
      con.setConnectionURI(URIService.createConnectionURI(con));
      con = connectionRepository.saveAndFlush(con);

      // TODO: do we save the connection content? where? as a chat content?
    }

    return con;
  }
 private void handleConnect() {
   try {
     int program_version = ois.readInt();
     port = ois.readInt();
     address = listenSocket.getInetAddress();
     netCode = ois.readInt();
     Connection c = checkConnectionNetCode();
     if (c != null) {
       oos.writeInt(ALREADY_CONNECTED);
       oos.flush();
       System.out.println("->ALREADY_CONNECTED"); // $NON-NLS-1$
     } else {
       if (isAcceptingConnections()) {
         if (connections.size() < Utils.getMAX_CONNECTIONS()) {
           if (Utils.VERSION == program_version) {
             Connection newConnection = newConnection();
             if (newConnection != null) {
               oos.writeInt(CONNECTED);
               newConnection.setState(Connection.STATE_CONNECTED);
               System.out.println("->CONNECTED"); // $NON-NLS-1$
             } else {
               oos.writeInt(ALREADY_CONNECTED);
               System.out.println("->ALREADY_CONNECTED"); // $NON-NLS-1$
             }
             oos.flush();
           } else {
             oos.writeInt(INCOMPATIBLE_PROGRAM_VERSION);
             oos.flush();
             System.out.println("->INCOMPATIBLE_PROGRAM_VERSION"); // $NON-NLS-1$
           }
         } else {
           oos.writeInt(TOO_MANY_CONNECTIONS);
           oos.flush();
           System.out.println("->TOO_MANY_CONNECTIONS"); // $NON-NLS-1$
         }
       } else {
         oos.writeInt(NOT_ACCEPTING_CONNECTIONS);
         oos.flush();
         System.out.println("->NOT_ACCEPTING_CONNECTIONS"); // $NON-NLS-1$
       }
     }
   } catch (IOException ex) {
     System.out.println(ex.getMessage());
   }
 }
  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());
      /*if(!eventType.isMessageAllowed(con.getState())){
        throw new ConnectionAlreadyExistsException(con.getConnectionURI(), con.getNeedURI(), con.getRemoteNeedURI());
      }*/ else {
        // TODO: Move this to the transition() - Method in ConnectionState
        con.setState(con.getState().transit(eventType));
        con = connectionRepository.saveAndFlush(con);
      }
    }

    return con;
  }