Esempio n. 1
0
    @Override
    public void run() {
      String message = null;

      try {
        in = new Scanner(socket.getInputStream());
        out = new PrintStream(socket.getOutputStream());

        while (true) {
          message = in.nextLine();
          if (message.equals("quit")) {
            messageDispatcher.send("즐거운 하루되세요.");
            break;
          }
          messageDispatcher.send(message);
        }

      } catch (Exception e) {
        System.out.println("클라이언트 통신 오류!");
      } finally {
        try {
          in.close();
        } catch (Exception e) {
        }
        try {
          out.close();
        } catch (Exception e) {
        }
        try {
          socket.close();
        } catch (Exception e) {
        }
      }
    }
  @Override
  public void decideAndSumitMsgToSend() {
    List<Obstacle> obstacles = intelligent_unit.getObstacles();
    int obstacle_num = obstacles.size();
    List<Threat> threats = intelligent_unit.getThreats();
    int threat_num = threats.size();
    List<Conflict> conflicts = intelligent_unit.getConflicts();
    int conflict_num = conflicts.size();

    List<Attacker> attackers = World.getAttackers();
    int attacker_num = attackers.size();
    for (int i = 0; i < attacker_num; i++) {
      Attacker attacker = attackers.get(i);
      KnowledgeInterface kb = attacker.getKb();
      Rectangle attacker_rect = null;
      Target attacker_target = attacker.getTarget_indicated_by_role();
      if (attacker_target != null) {
        attacker_rect =
            RectangleUtil.findMBRRect(
                attacker.getCenter_coordinates(), attacker_target.getCoordinates());
      }

      for (int j = 0; j < obstacle_num; j++) {
        Obstacle obstacle = obstacles.get(j);
        if (!kb.containsObstacle(obstacle)) {
          super.addRecvMessage(i, obstacle);
        }
      }

      for (int j = 0; j < threat_num; j++) {
        Threat threat = threats.get(j);
        if (!kb.containsThreat(threat)) {
          this.addRecvMessage(i, threat);
        }
      }

      if (attacker_rect == null) {
        continue;
      }
      for (int j = 0; j < conflict_num; j++) {
        Conflict conflict = conflicts.get(j);
        int uav_index = conflict.getUav_index();
        Attacker conflict_uav = attackers.get(uav_index);
        Target conflict_uav_target = conflict_uav.getTarget_indicated_by_role();
        if (conflict_uav_target != null && uav_index != attacker.getIndex()) {
          Rectangle conflict_uav_rect =
              RectangleUtil.findMBRRect(
                  conflict_uav.getCenter_coordinates(), conflict_uav_target.getCoordinates());
          if (attacker_rect.intersects(conflict_uav_rect)) {
            super.addRecvMessage(i, conflict);
          }
        }
      }
    }
  }
Esempio n. 3
0
  /**
   * Test instance of TestEnv2.
   *
   * @throws Exception If the test is a failure.
   */
  @Test
  public void testDispatcher2() throws Exception {
    // test with inherited annotation without explicit class specification
    IFD ifd = new TestIFD();
    Environment env = new TestEnv2();
    MessageDispatcher disp = new MessageDispatcher(env);

    env.setIFD(ifd);

    Object req = new EstablishContext();
    Object res = disp.deliver(req);

    assertTrue(res instanceof EstablishContextResponse);
  }
 @SuppressWarnings("unchecked")
 private <T> void addTopicListener(
     String topic, Object inner, ByteArrayConverter<T> converter, TypedListener<T> listener)
     throws ConnectorException {
   synchronized (messageDispatcher) {
     MessageDispatcher<T> dispatcher = messageDispatcher.get(topic);
     if (dispatcher == null) {
       ConnectorSession session = connection.createSession();
       ConnectorConsumer consumer = session.createConsumer(session.createTopic(topic));
       messageDispatcher.put(topic, dispatcher = new MessageDispatcher<T>(consumer, converter));
     }
     dispatcher.addListener(inner, listener);
   }
 }
 private void removeTopicListener(String topic, Object inner) {
   synchronized (messageDispatcher) {
     MessageDispatcher dispatcher = messageDispatcher.get(topic);
     if (dispatcher != null) {
       dispatcher.removeListener(inner);
       if (!dispatcher.isListened()) {
         messageDispatcher.remove(topic);
         try {
           dispatcher.getConsumer().close();
         } catch (ConnectorException e) {
         }
       }
     }
   }
 }
Esempio n. 6
0
 /**
  * Called when message is incoming. Dispatches message according to message dispatcher
  *
  * @param msg The message to dispatch
  * @param port the port from which the message came
  * @return true if dispatch successful
  */
 public boolean handleMessage(Msg msg, String port) {
   if (m_dispatcher == null) {
     logger.error("{} no dispatcher for msg {}", m_name, msg);
     return false;
   }
   return (m_dispatcher.dispatch(msg, port));
 }
  @Test(timeout = 300000)
  public void testMessageOrder() throws InterruptedException {
    int numberOfMessages = 100;
    final CountDownLatch latch = new CountDownLatch(numberOfMessages);

    MessageDispatcher<std_msgs.Int32> messageDispatcher =
        new MessageDispatcher<std_msgs.Int32>(lazyMessages, executorService);
    messageDispatcher.addListener(
        new MessageListener<std_msgs.Int32>() {
          private AtomicInteger count = new AtomicInteger();

          public void onNewMessage(Int32 message) {
            if (this.count.compareAndSet(message.getData(), message.getData() + 1)) {
              latch.countDown();
            } else {
              fail(
                  String.format(
                      "Expected message data not equal to actual data: %d != %d",
                      count.get(), message.getData()));
            }
            try {
              // Sleeping allows the queue to fill up a bit by slowing down the
              // consumer.
              Thread.sleep(5);
            } catch (InterruptedException e) {
            }
          }
        },
        QUEUE_CAPACITY);
    executorService.execute(messageDispatcher);

    for (int i = 0; i < numberOfMessages; i++) {
      final int count = i;
      std_msgs.Int32 message = messageFactory.newFromType(std_msgs.Int32._TYPE);
      message.setData(count);
      lazyMessages.addLast(new LazyMessage<std_msgs.Int32>(message));
    }

    assertTrue(latch.await(1, TimeUnit.SECONDS));
  }
Esempio n. 8
0
  private void dispose(Throwable throwable) {
    synchronized (this) {
      if (disposed) {
        return;
      }
      disposed = true;
    }

    notifyListeners();
    for (Iterator<DisposeListener> i = disposeListeners.iterator(); i.hasNext(); ) {
      i.next().notifyDispose(this);
    }

    _iProtocol.terminate();

    try {
      _messageDispatcher.terminate();

      try {
        _xConnection.close();
      } catch (com.sun.star.io.IOException e) {
        System.err.println(getClass().getName() + ".dispose - IOException:" + e);
      }

      if (Thread.currentThread() != _messageDispatcher && _messageDispatcher.isAlive()) {
        _messageDispatcher.join(1000);
        if (_messageDispatcher.isAlive()) {
          _messageDispatcher.interrupt();
          _messageDispatcher.join();
        }
      }

      // interrupt all jobs queued by this bridge
      _iThreadPool.dispose(throwable);

      // release all out-mapped objects and all in-mapped proxies:
      freeHolders();
      // assert _java_environment instanceof java_environment;
      ((java_environment) _java_environment).revokeAllProxies();

      proxyFactory.dispose();

      if (DEBUG) {
        if (_life_count.get() != 0) {
          System.err.println(
              getClass().getName() + ".dispose - life count (proxies left):" + _life_count);
        }
        _java_environment.list();
      }

      // clear members
      _xConnection = null;
      _java_environment = null;
      _messageDispatcher = null;
    } catch (InterruptedException e) {
      System.err.println(getClass().getName() + ".dispose - InterruptedException:" + e);
    }
  }
Esempio n. 9
0
 public java_remote_bridge(
     IEnvironment java_environment, IEnvironment remote_environment, Object[] args)
     throws Exception {
   _java_environment = java_environment;
   String proto = (String) args[0];
   _xConnection = (XConnection) args[1];
   _xInstanceProvider = (XInstanceProvider) args[2];
   if (args.length > 3) {
     _name = (String) args[3];
   }
   String attr;
   int i = proto.indexOf(',');
   if (i >= 0) {
     protocol = proto.substring(0, i);
     attr = proto.substring(i + 1);
   } else {
     protocol = proto;
     attr = null;
   }
   _iProtocol =
       (IProtocol)
           Class.forName("com.sun.star.lib.uno.protocols." + protocol + "." + protocol)
               .getConstructor(
                   new Class[] {
                     IBridge.class, String.class, InputStream.class, OutputStream.class
                   })
               .newInstance(
                   new Object[] {
                     this,
                     attr,
                     new XConnectionInputStream_Adapter(_xConnection),
                     new XConnectionOutputStream_Adapter(_xConnection)
                   });
   proxyFactory = new ProxyFactory(this, this);
   _iThreadPool = ThreadPoolManager.create();
   _messageDispatcher = new MessageDispatcher();
   _messageDispatcher.start();
   _iProtocol.init();
 }
Esempio n. 10
0
 /**
  * Helper method; registers a message handler.
  *
  * @param type The message type.
  * @param handler The message handler.
  * @param <T> The generic message type.
  */
 public <T extends Message> void registerMessageHandler(Class<T> type, MessageHandler<T> handler) {
   dispatcher.registerHandler(type, handler);
 }
Esempio n. 11
0
  @Test
  public void onMessage() {
    toTest.onMessage(msg(HELLO, "Hello, player #1."));
    verify(controller).started(1);
    verify(controller).rename();

    toTest.onMessage(msg(PLACE_SHIPS));
    verify(controller).placeShips();

    toTest.onMessage(msg(YOUR_TURN));
    verify(controller).myTurn();

    toTest.onMessage(msg(ENEMY_SHIP_HIT));
    verify(controller).hit(eq((Coord) null));
    toTest.onMessage(msg(ENEMY_SHIP_HIT, "Enemy ship hit at 51."));
    verify(controller).hit(eq(new Coord("51")));

    toTest.onMessage(msg(ENEMY_SHIP_MISSED));
    verify(controller).missed();
    toTest.onMessage(msg(TORPEDO));
    verify(controller, times(2)).missed();

    toTest.onMessage(msg(DRONE, "The drone found 3 ship segments at 51!"));
    verify(controller).spy(eq(new SpyArea(new Coord("51"), 3)));

    toTest.onMessage(msg(YOUR_SHIP_HIT, "The enemy hits at 51."));
    verify(controller).enemyHit(eq(new Coord("51")));
    toTest.onMessage(msg(YOUR_SHIP_HIT, "Your burned at 51!"));
    verify(controller).enemyBurnHit(eq(new Coord("51")));

    toTest.onMessage(msg(YOUR_SHIP_MISSED, "Enemy shoots at 51 and misses."));
    verify(controller).enemyMissed(eq(new Coord("51")));

    toTest.onMessage(msg(YOUR_SHIP_SUNK, "at 51!"));
    verify(controller).enemySunk(eq(new Coord("51")));

    toTest.onMessage(msg(DRONEEE, "at 51!"));
    verify(controller).enemySpy(eq(new SpyArea(new Coord("51"))));
  }
 public void dispatchMessage(Message message) {
   messageDispatcher.dispatch(message);
   messageProvider.free(message);
 }