public void end() {
    done = true;

    printStatistics();
    this.interrupt();

    synchronized (workerThreads) {
      workToDo.clear();
      workerThreads.notifyAll();
    }

    for (int i = 0; i < workerThreads.size(); i++) {
      ((WorkerThread) workerThreads.get(i)).done();
    }
  }
  /** {@inheritDoc} */
  public void destroy() {
    started.set(false);
    destroyed.set(true);
    releaseExternalResources();
    if (notifierFuture != null) {
      notifierFuture.cancel(true);
    }

    if (asyncWriteFuture != null) {
      asyncWriteFuture.cancel(true);
    }

    if (bc != null) {
      bc.destroy();
    }

    if (broadcasterCache != null) {
      broadcasterCache.stop();
    }
    resources.clear();
    broadcastOnResume.clear();
    messages.clear();
    asyncWriteQueue.clear();
    delayedBroadcast.clear();
    broadcasterCache = null;

    if (BroadcasterFactory.getDefault() != null) {
      BroadcasterFactory.getDefault().remove(this, name);
    }

    if (currentLifecycleTask != null) {
      currentLifecycleTask.cancel(true);
    }
  }
 @Override
 protected void finalize() throws Throwable {
   super.finalize();
   synchronized (DevMountInfo.class) {
     mInternalPathList.clear();
     mExternalPathList.clear();
     mExecutor.shutdown();
     INSTANCE = null;
   }
 }
Example #4
0
  @Override
  public void update(float tpf) {
    super.update(tpf);

    runningCommands.addAll(pendingCommands);
    pendingCommands.clear();
    for (PHATDeviceCommand bc : runningCommands) {
      bc.run(app);
    }
    runningCommands.clear();
  }
Example #5
0
 @SuppressWarnings("synthetic-access")
 @Override
 public void clear() {
   super.clear();
   getSaveInLdapAction().setEnabled(false);
   firePropertyChange(ISaveablePart.PROP_DIRTY);
 }
 @Override
 public void cancelAllTasks() {
   for (PipeTask task : queuedTasks) {
     task.cancel0();
   }
   queuedTasks.clear();
 }
  /** 停止所有任务 */
  public void stopAllTask() {
    // 从下载队列移除
    for (Map.Entry<String, DownloadHttpTask> entry : mDownloadingTaskMap.entrySet()) {
      DownloadHttpTask task = entry.getValue();
      task.setInterrupt(true);
    }
    mDownloadingTaskMap.clear();

    Iterator<DownloadInfo> downloadingIt = mDownloadingTasks.iterator();
    while (downloadingIt.hasNext()) {
      DownloadInfo b = downloadingIt.next();
      b.setState(DownloadInfo.PAUSE);
      downloadingIt.remove();
      mPausingTasks.add(b); // 放入暂停队列
    }
    mDownloadingTasks.clear();

    // 从等待队列移除
    Iterator<DownloadInfo> waitIt = mWaitTasks.iterator();
    while (waitIt.hasNext()) {
      DownloadInfo b = waitIt.next();
      b.setState(DownloadInfo.PAUSE);
      waitIt.remove();
      mPausingTasks.add(b); // 放入暂停队列
      break;
    }
    mWaitTasks.clear();
  }
 /** Completely reset the instance to its initial state. */
 public void reset() {
   isResumed.set(false);
   isCancelled.set(false);
   isInScope.set(true);
   isSuspendEvent.set(false);
   listeners.clear();
   action.type(Action.TYPE.CREATED);
 }
  protected void sendUpdates() {
    // get the current version
    int currentVersion = version.get();
    //
    boolean persist = isPersistentObject();
    // get read-only version of events
    ConcurrentLinkedQueue<ISharedObjectEvent> events =
        new ConcurrentLinkedQueue<ISharedObjectEvent>(ownerMessage.getEvents());
    // clear out previous events
    ownerMessage.getEvents().clear();
    //
    if (!events.isEmpty()) {
      // Send update to "owner" of this update request
      SharedObjectMessage syncOwner = new SharedObjectMessage(null, name, currentVersion, persist);
      syncOwner.addEvents(events);
      if (source != null) {
        // Only send updates when issued through RTMP request
        Channel channel = ((RTMPConnection) source).getChannel((byte) 3);
        if (channel != null) {
          // ownerMessage.acquire();
          channel.write(syncOwner);
          log.debug("Owner: {}", channel);
        } else {
          log.warn("No channel found for owner changes!?");
        }
      }
    }
    // clear owner events
    events.clear();
    // get read-only version of sync events
    events.addAll(syncEvents);
    // clear out previous events
    syncEvents.clear();
    if (!events.isEmpty()) {
      // Synchronize updates with the current listeners of this shared
      for (IEventListener listener : currentListeners) {
        if (listener == source) {
          // Don't re-send update to active client
          log.debug("Skipped {}", source);
          continue;
        }
        if (!(listener instanceof RTMPConnection)) {
          log.warn("Can't send sync message to unknown connection {}", listener);
          continue;
        }
        // Create a new sync message for every client to avoid
        // concurrent access through multiple threads
        // TODO: perhaps we could cache the generated message
        SharedObjectMessage syncMessage =
            new SharedObjectMessage(null, name, currentVersion, persist);
        syncMessage.addEvents(events);

        Channel channel = ((RTMPConnection) listener).getChannel((byte) 3);
        log.debug("Send to {}", channel);
        channel.write(syncMessage);
      }
    }
  }
Example #10
0
 public void clearAllMessages() {
   if (messages.size() > 0) {
     Debug.warn(
         "Message inbox of "
             + username
             + " contained "
             + messages.size()
             + " extra messages, discarding...");
   }
   messages.clear();
 }
Example #11
0
  /** This method cleans fields that are irrelevant for the archived execution attempt. */
  public void prepareForArchiving() {
    if (assignedResource != null && assignedResource.isAlive()) {
      throw new IllegalStateException(
          "Cannot archive Execution while the assigned resource is still running.");
    }
    assignedResource = null;

    executionContext = null;

    partialInputChannelDeploymentDescriptors.clear();
    partialInputChannelDeploymentDescriptors = null;
  }
  protected void broadcastOnResume(AtmosphereResource<?, ?> r) {
    Iterator<Entry> i = broadcastOnResume.iterator();
    while (i.hasNext()) {
      Entry e = i.next();
      e.multipleAtmoResources = r;
      push(e);
    }

    if (resources.isEmpty()) {
      broadcastOnResume.clear();
    }
  }
Example #13
0
 /** Copies the next values to the snapshot */
 @Override
 public void copySnapshot() {
   if (dirty.size() > 0) {
     snapshot.clear();
     synchronized (live) {
       for (T o : live) {
         snapshot.add(o);
       }
     }
   }
   dirty.clear();
 }
Example #14
0
  synchronized void send(JSONStreamAware response) {
    if (asyncContext == null) {

      if (isInactive) {
        // user not seen recently, no responses should be collected
        return;
      }
      if (pendingResponses.size() > 1000) {
        pendingResponses.clear();
        // stop collecting responses for this user
        isInactive = true;
        if (secretPhrase == null) {
          // but only completely remove users that don't have unlocked accounts
          Users.remove(this);
        }
        return;
      }

      pendingResponses.offer(response);

    } else {

      JSONArray responses = new JSONArray();
      JSONStreamAware pendingResponse;
      while ((pendingResponse = pendingResponses.poll()) != null) {

        responses.add(pendingResponse);
      }
      responses.add(response);

      JSONObject combinedResponse = new JSONObject();
      combinedResponse.put("responses", responses);

      asyncContext.getResponse().setContentType("text/plain; charset=UTF-8");

      try (Writer writer = asyncContext.getResponse().getWriter()) {
        combinedResponse.writeJSONString(writer);
      } catch (IOException e) {
        Logger.logMessage("Error sending response to user", e);
      }

      asyncContext.complete();
      asyncContext = null;
    }
  }
  private void processCameraData(
      final byte[] cameraData, final int imageWidth, final int imageHeight) {

    cameraPreviewCallbackQueue.clear();
    boolean offerSuccess =
        cameraPreviewCallbackQueue.offer(
            new Runnable() {
              @Override
              public void run() {
                long start = System.nanoTime();

                // Convert data to JPEG and compress
                YuvImage image =
                    new YuvImage(cameraData, ImageFormat.NV21, imageWidth, imageHeight, null);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                Rect area = new Rect(0, 0, imageWidth, imageHeight);
                image.compressToJpeg(area, IMAGE_QUALITY, out);
                byte[] jpegVideoFrameData = out.toByteArray();

                // rotate image
                byte[] rotatedCameraData =
                    rotateImage(jpegVideoFrameData, imageWidth, imageHeight, currentCameraId);
                if (rotatedCameraData.length == 0) {
                  return;
                }

                // send data to the opponent
                //
                cameraDataListener.onCameraDataReceive(rotatedCameraData);
                //
                //

                // close stream
                try {
                  out.close();
                } catch (IOException e) {
                  e.printStackTrace();
                }
              }
            });
  }
 private void processNextClientRequest() {
   QueueEntry qe = (QueueEntry) qClientRequests.poll();
   if (qe != null) {
     EventSocket sock = qe.sock;
     String message = qe.message;
     boolean isAllowed = false;
     LockHolder lock = getLockForCommand(message);
     if (lock != null) {
       // if the lock exists check whether the user is allowed to use this command
       int[] privs = lock.getAllowedPrivileges();
       for (int priv : privs) if (priv == sock.getPrivilege()) isAllowed = true;
       if (isAllowed) {
         if (lockHolder == null) { // if no lock is set we try to execute the command
           setLock(lock.setLockAction(message));
           Debg.print("lock set and executed");
         } else { // if a lock is already set the command might contain an abort message
           String cmd = Parser.getValue(message, NanoComm.COMMAND_CMD);
           String[] abortCmds = lockHolder.getAbortCommands();
           boolean isAbortable = false;
           if (abortCmds != null)
             for (int i = 0; i < abortCmds.length; i++) {
               if (cmd.equals(abortCmds[i])) isAbortable = true;
             }
           if (isAbortable) {
             setLock(lockHolder.takeAbortActions("Overwriting command has been sent"));
           } else sock.sendClientInfo("Please be patient, the remote experiment is still busy");
         }
       } else sock.sendClientInfo("Sorry, you are not allowed to use this command!");
     } else Debg.print("No lock found for: " + message);
   }
   if (qClientRequests.size() > 10) {
     Debg.err(
         "I have been flooded by "
             + qClientRequests.size()
             + " client requests! I dropped everything except for the oldest one");
     qe = (QueueEntry) qClientRequests.poll();
     qClientRequests.clear();
     qClientRequests.add(qe);
   }
 }
  @Override
  protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    final int paddingTop = getPaddingTop();
    if (needScrollCorrection) {
      slide(null, 1, false);
      needScrollCorrection = false;
      pendingList.clear();
    }

    int childTop = paddingTop;
    int childLeft = mOffsetLeft;

    View iconView = channelIconInflateResult.rootView;
    int childWidth = iconView.getMeasuredWidth();
    int childHeight = iconView.getMeasuredHeight();

    ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) getLayoutParams();
    childLeft += lp.leftMargin;

    ViewGroup.MarginLayoutParams lpChild =
        (ViewGroup.MarginLayoutParams) iconView.getLayoutParams();
    childTop = getHeight() - childHeight - lpChild.bottomMargin;
    childLeft += (lpChild.leftMargin);
    setChildFrame(iconView, childLeft, childTop, childWidth, childHeight);
    childLeft += (childWidth + lpChild.rightMargin + lpChild.leftMargin);
    // childLeft -= mScrollDistance;

    for (int i = 0; i < videoListViews.size(); i++) {
      final View child = getChildAt(i);
      childWidth = child.getMeasuredWidth();
      childHeight = child.getMeasuredHeight();

      lpChild = (ViewGroup.MarginLayoutParams) child.getLayoutParams();
      childTop = getHeight() - childHeight - lpChild.bottomMargin;
      childLeft += (lpChild.leftMargin);
      setChildFrame(child, childLeft, childTop, childWidth, childHeight);
      childLeft += (childWidth + lpChild.rightMargin);
    }
  }
  private void executeInit(Context context) {
    StorageManager mStorageManager =
        (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
    if (mStorageManager != null) {
      Class<?> mStorageVolume = null;
      Method mGetVolumeListMethod = null;
      Method mGetVolumeStateMethod = null;
      Method mGetPathMethod = null;
      Method mIsRemovableMethod = null;
      Object[] mStorageVolumeList = null;
      try {
        mStorageVolume = Class.forName(CLASS_NAME);
        mGetVolumeListMethod =
            mStorageManager.getClass().getMethod(METHOD_GET_VOLUME_LIST, new Class[0]);
        mGetVolumeStateMethod =
            mStorageManager
                .getClass()
                .getMethod(METHOD_GET_VOLUME_STATE, new Class[] {String.class});
        mIsRemovableMethod = mStorageVolume.getMethod(METHOD_IS_REMOVABLE, new Class[0]);
        mGetPathMethod = mStorageVolume.getMethod(METHOD_GET_PATH, new Class[0]);

        mStorageVolumeList = (Object[]) mGetVolumeListMethod.invoke(mStorageManager, new Object[0]);

        boolean mIsRemovable = false;

        if (mStorageVolumeList != null && mStorageVolumeList.length > 0) {
          int mStorageVolumeCount = mStorageVolumeList.length;

          Log.i(TAG, "init() === > StorageVolume Count = " + mStorageVolumeCount);

          mInternalPathList.clear();
          mExternalPathList.clear();

          for (int i = 0; i < mStorageVolumeCount; ++i) {
            String mStoragePath =
                (String) mGetPathMethod.invoke(mStorageVolumeList[i], new Object[0]);
            mIsRemovable =
                ((Boolean) mIsRemovableMethod.invoke(mStorageVolumeList[i], new Object[0]))
                    .booleanValue();
            if (!TextUtils.isEmpty(mStoragePath)) {
              String state =
                  (String)
                      mGetVolumeStateMethod.invoke(mStorageManager, new Object[] {mStoragePath});
              if ((state != null) && (state.equals(MOUNTED))) {
                if (mIsRemovable) {
                  Log.i(TAG, "init() === > external storage path = (" + mStoragePath + ")");
                  mExternalPathList.add(mStoragePath);
                } else {
                  Log.i(TAG, "init() === > internal storage path = (" + mStoragePath + ")");
                  mInternalPathList.add(mStoragePath);
                }
              }
            }
          }
        }
      } catch (ClassNotFoundException e) {
        handleInvalid();
        Log.e(TAG, "init() === > Exception:ClassNotFoundException");
      } catch (NoSuchMethodException e) {
        handleInvalid();
        Log.e(TAG, "init() === > Exception:NoSuchMethodException");
      } catch (IllegalArgumentException e) {
        handleInvalid();
        Log.e(TAG, "init() === > Exception:IllegalArgumentException");
      } catch (IllegalAccessException e) {
        handleInvalid();
        Log.e(TAG, "init() === > Exception:IllegalAccessException");
      } catch (InvocationTargetException e) {
        handleInvalid();
        Log.e(TAG, "init() === > Exception:InvocationTargetException");
      }
    } else {
      handleInvalid();
      Log.e(TAG, "init() === > can't get storage manager");
    }
    initSDCardPath();
  }
  /** {@inheritDoc} */
  @Override
  public synchronized AtmosphereResource resume() {
    // We need to synchronize the method because the resume may occurs at the same time a message is
    // published
    // and we will miss that message. The DefaultBroadcaster synchronize on that method before
    // writing a message.
    try {
      if (!isResumed && isInScope) {
        action.type(Action.TYPE.RESUME);
        isResumed = true;

        // We need it as Jetty doesn't support timeout
        Broadcaster b = getBroadcaster(false);
        if (!b.isDestroyed() && b instanceof DefaultBroadcaster) {
          ((DefaultBroadcaster) b).broadcastOnResume(this);
        }

        notifyListeners();

        try {
          if (!b.isDestroyed()) {
            broadcaster.removeAtmosphereResource(this);
          }
        } catch (IllegalStateException ex) {
          logger.warn("Unable to resume", this);
          logger.debug(ex.getMessage(), ex);
        }

        if (b.getScope() == Broadcaster.SCOPE.REQUEST) {
          logger.debug("Broadcaster's scope is set to request, destroying it {}", b.getID());
          b.destroy();
        }

        // Resuming here means we need to pull away from all other Broadcaster, if they exists.
        if (config.getBroadcasterFactory() != null) {
          config.getBroadcasterFactory().removeAllAtmosphereResource(this);
        }

        try {
          req.setAttribute(ApplicationConfig.RESUMED_ON_TIMEOUT, Boolean.FALSE);
        } catch (Exception ex) {
          logger.debug("Resume exception: Cannot resume an already resumed/cancelled request", ex);
        } finally {
          try {
            Meteor m = (Meteor) req.getAttribute(METEOR);
            if (m != null) {
              m.destroy();
            }
          } catch (Exception ex) {
            logger.debug(
                "Meteor resume exception: Cannot resume an already resumed/cancelled request", ex);
          }
        }

        if (req.getAttribute(PRE_SUSPEND) == null) {
          asyncSupport.action(this);
        }
      } else {
        logger.debug("Cannot resume an already resumed/cancelled request {}", this);
      }
    } catch (Throwable t) {
      logger.trace("Wasn't able to resume a connection {}", this, t);
    }
    notifyListeners(new AtmosphereResourceEventImpl(this, true, false));
    listeners.clear();
    return this;
  }
Example #20
0
 public void clearAllTasks() {
   mTaskQueue.clear();
 }
 public void clear() throws IOException {
   queue.clear();
 }
  @Override
  public AtmosphereResource resume() {

    if (!isSuspended()) {
      logger.warn("AtmosphereResource {} not suspend, cannot resume it.", uuid());
      return this;
    }

    try {
      if (!isResumed.getAndSet(true) && isInScope.get()) {
        logger.trace("AtmosphereResource {} is resuming", uuid());

        action.type(Action.TYPE.RESUME);

        // We need it as Jetty doesn't support timeout
        Broadcaster b = getBroadcaster(false);
        if (!b.isDestroyed() && b instanceof DefaultBroadcaster) {
          ((DefaultBroadcaster) b).broadcastOnResume(this);
        }

        notifyListeners();

        try {
          if (!b.isDestroyed()) {
            broadcaster.removeAtmosphereResource(this);
          }
        } catch (IllegalStateException ex) {
          logger.warn("Unable to resume", this);
          logger.debug(ex.getMessage(), ex);
        }

        if (b.getScope() == Broadcaster.SCOPE.REQUEST) {
          logger.debug("Broadcaster's scope is set to request, destroying it {}", b.getID());
          b.destroy();
        }

        // Resuming here means we need to pull away from all other Broadcaster, if they exists.
        if (config.getBroadcasterFactory() != null) {
          config.getBroadcasterFactory().removeAllAtmosphereResource(this);
        }

        try {
          req.setAttribute(ApplicationConfig.RESUMED_ON_TIMEOUT, Boolean.FALSE);
        } catch (Exception ex) {
          logger.debug("Resume exception: Cannot resume an already resumed/cancelled request", ex);
        } finally {
          try {
            Meteor m = (Meteor) req.getAttribute(METEOR);
            if (m != null) {
              m.destroy();
            }
          } catch (Exception ex) {
            logger.debug(
                "Meteor resume exception: Cannot resume an already resumed/cancelled request", ex);
          }
        }

        if (req.getAttribute(PRE_SUSPEND) == null) {
          asyncSupport.action(this);
        }
      } else {
        logger.trace("Already resumed {}", this);
        return this;
      }
    } catch (Throwable t) {
      logger.trace("Wasn't able to resume a connection {}", this, t);
    }
    listeners.clear();
    return this;
  }
Example #23
0
 public void reset() {
   overwriteQueue.clear();
   overwriteBackup.clear();
 }
Example #24
0
 public void clear() {
   QUEUE.clear();
   releaseCalls.set(0);
   newBufferCalls.set(0);
 }
 @Override
 public AtmosphereResource removeEventListeners() {
   listeners.clear();
   return this;
 }
  private void sendDataToMembers(ArrayList memberList) {
    if (Logger.logLevel == -55) {
      for (int i = 0; i < memberList.size(); i++) {
        ConferenceMember m = (ConferenceMember) memberList.get(i);

        Logger.println("conf " + getName() + ": " + m);
      }
      Logger.println("wt size " + workerThreads.size() + " sender threads " + senderThreads);
    }

    if (workerThreads.size() > 1 && workerThreads.size() != senderThreads) {
      /*
       * Stop old threads
       * XXX We could just stop the extra threads or add new ones
       * rather than stopping all of them.
       */
      if (Logger.logLevel == -55) {
        Logger.println("Stopping sender worker threads " + workerThreads.size());
      }

      for (int i = 0; i < workerThreads.size(); i++) {
        ((WorkerThread) workerThreads.get(i)).done();
      }

      workerThreads.clear();
    }

    if (senderThreads <= 1) {
      singleThreadSendDataToMembers(memberList);
      return;
    }

    CountDownLatch doneSignal = new CountDownLatch(workerThreads.size());

    if (workerThreads.size() != senderThreads) {
      /*
       * Start new threads
       */
      for (int i = 0; i < senderThreads; i++) {
        workerThreads.add(new WorkerThread(i, doneSignal));
      }

      Logger.println("Started " + senderThreads + " sender threads");
    }

    workToDo.clear();

    for (int i = 0; i < memberList.size(); i++) {
      ConferenceMember member = (ConferenceMember) memberList.get(i);

      if (member.getMemberSender().memberIsReadyForSenderData()) {
        workToDo.add(member);
      }
    }

    /*
     * Start all of the worker threads
     */
    for (int i = 0; i < workerThreads.size(); i++) {
      WorkerThread workerThread = (WorkerThread) workerThreads.get(i);

      workerThread.setLatch(doneSignal);

      synchronized (workerThread) {
        workerThread.notify();
      }
    }

    if (!done) {
      try {
        doneSignal.await(); // wait for all to finish
      } catch (InterruptedException e) {
      }
    }
  }
 public void clearqueue() {
   movequeue.clear();
 }
Example #28
0
  public void handleNotification(INotification notification) {
    //		Logger.debug("@ClientMediator.handleNotification:noti="+notification.getBody());
    String noname = notification.getName();
    if (noname == Const.TICK) {
      if (destroyd) return;
      long t = TimerCmd.timeStamp;

      String[] ary;
      int st, ed;
      if (_lastRotTank != null) {
        ary = _lastRotTank.split(" ");
        st = Integer.parseInt(ary[0]);
        ed = st + Integer.parseInt(ary[6]);
        if (t <= ed && t >= st) {
          int ist = Integer.parseInt(ary[0]);
          if (_move.size() > 0) {
            st = Integer.parseInt(_move.peek().split(" ")[0]);
            while (st < ist && _move.size() > 0) {
              _move.poll();
              if (_move.size() == 0) break;
              st = Integer.parseInt(_move.peek().split(" ")[0]);
            }
          }
        }
      }
      if (_move.size() > 0) {
        ary = _move.peek().split(" ");
        st = Integer.parseInt(ary[0]);
        ed = st + Integer.parseInt(ary[8]);

        while ((t > ed) && _move.size() > 0) {
          //					Logger.debug("@TankMediator.handleNotification: t = " + t + " st = " + st + "
          // ed="+ed);
          String p = (String) _move.poll();
          Logger.debug("ClientMediator.TICK _move.poll=" + p);
          if (_move.size() == 0) break;
          ary = _move.peek().split(" ");
          st = Integer.parseInt(ary[0]);
          ed = st + Integer.parseInt(ary[8]);
        }

        if (_move.size() > 0) {
          String[] li = (String[]) _move.toArray(new String[0]);
          for (int i = li.length - 1; i >= 0; i--) {
            String s = li[i];
            ary = s.split(" ");
            st = Integer.parseInt(ary[0]);
            ed = st + Integer.parseInt(ary[8]);
            if (t <= ed && t >= st) {
              if (t == st) { // ed==st in this situation
                _state.x = (int) Float.parseFloat(ary[4]);
                _state.y = (int) Float.parseFloat(ary[5]);
                _nextX = _state.x;
                _nextY = _state.y;
              } else {
                float sx = Float.parseFloat(ary[4]);
                float ex = Float.parseFloat(ary[6]);
                float sy = Float.parseFloat(ary[5]);
                float ey = Float.parseFloat(ary[7]);
                double eco = 1.0 * (t - st) / (ed - st);
                _state.x = (int) (sx + (ex - sx) * eco);
                _state.y = (int) (sy + (ey - sy) * eco);
                double neco = 1.0 * (t + 1 - st) / (ed - st);
                _nextX = (sx + (ex - sx) * neco);
                _nextY = (sy + (ey - sy) * neco);
              }
              while (_move.size() > 1) _move.poll();
              break;
            }
          }
        }
      }
      if (_state != null) {
        ConcurrentHashMap<Integer, BulletState> bs =
            ((ServerBulletMediator) (appFacade().retrieveMediator(Const.SERVER_BULLET_MEDIATOR)))
                .getBullets();
        for (Enumeration enu = bs.keys(); enu.hasMoreElements(); ) {
          int id = (Integer) enu.nextElement();
          BulletState blt = bs.get(id);
          if (Texter.distance(blt.x, blt.y, _state.x, _state.y) < 16) {
            this.sendNotification(Const.BROAD_CAST, "destroy bullet " + id, null);
            _state.life -= 100;
            if (_state.life <= 0) {
              this.sendNotification(Const.BROAD_CAST, "destroy tank " + _state.tankID, null);
            } else {
              this.sendNotification(
                  Const.BROAD_CAST, "set-life tank " + _state.tankID + " " + _state.life, null);
            }
          }
        }
      }

      // barrier and tank
      if (_state != null) {
        // colision detection
        //				Logger.only("ClientMediator.handleNotification: x="+_state.x+" y="+_state.y+"
        // nx="+_nextX+" ny="+_nextY+" "+Texter.sqrareDis(_nextX, _nextY, 470, 200)+"
        // "+Texter.sqrareDis(_state.x, _state.y, 470, 200));
        if (!Arena.canGo(_state.x, _state.y, _nextX, _nextY)) {
          Arena.addReq(_id, Const.STOP_MOVE, getState());
        }
        for (Enumeration enu = AcceptCmd.clients.elements(); enu.hasMoreElements(); ) {
          ClientMediator cmm = (ClientMediator) enu.nextElement();
          if (cmm.destroyd) return;
          int cmid = cmm.getID();
          if (cmid == _id) continue;
          TankState ts = cmm.getState();
          if (ts == null) continue;
          double curdis = Texter.distance(ts.x, ts.y, _state.x, _state.y);
          double netdis = Texter.distance(ts.x, ts.y, _nextX, _nextY);
          if (curdis < 40 && netdis < curdis) {
            Arena.addReq(_id, Const.STOP_MOVE, getState());
            Arena.addReq(cmid, Const.STOP_MOVE, ts);
          }
        }
      }

      // handle delayed first
      //			ary=_delayOrder.toArray(new String[0]);
      //			_delayOrder.clear();
      //			for(int i=0;i<ary.length;i++){
      //				Logger.only("delayArray: "+ary[i]);
      //				int ttt=Integer.parseInt(ary[i].split(" ")[0]);
      //				if(ttt==t){
      //					tellClientWithTime(ary[i]);
      //				}else if(ttt>t){
      //					_delayOrder.add(ary[i]);
      //				}
      //			}

    } else if (noname == Const.BROAD_CAST) {
      String s = (String) notification.getBody();
      String ary[] = s.split(" ");

      if (notification.getType() == Const.NO_PREFIX) {
        tellClientWithTime(s);
        return;
      } else if (s.indexOf("talk") > -1) {
        tellClient(s, 0);
        return;
      }
      if (_id == Integer.parseInt(ary[2])) {
        if (s.indexOf("rotate-gun") > -1) {
          _lastRotateGun = TimerCmd.timeStamp + " " + s;
          if (_state != null) _state.gunAngle = Float.parseFloat(_lastRotateGun.split(" ")[5]);
        } else if (s.indexOf("move tank") > -1) {
          Logger.debug("ClientMediator: move add s=" + s);
          int offset = Integer.parseInt(notification.getType());
          if (offset == 0) _move.clear();
          _move.add((TimerCmd.timeStamp + offset) + " " + s);
        } else if (s.indexOf("create tank") > -1) {
          _state =
              new TankState(
                  _id,
                  ary[3],
                  Integer.parseInt(ary[6]),
                  (int) Float.parseFloat(ary[8]),
                  (int) Float.parseFloat(ary[9]),
                  Float.parseFloat(ary[10]),
                  Float.parseFloat(ary[11]));
          _state.printState();
        } else if (s.indexOf("rotate-tank") > -1) {
          _lastRotTank = TimerCmd.timeStamp + " " + s;
          if (_state != null) _state.tankAngle = Float.parseFloat(_lastRotTank.split(" ")[5]);
        } else if (s.indexOf("destroy tank") > -1) {
          this.destroyd = true;
        }
      }
      if (notification.getType() != null) tellClient(s, Integer.parseInt(notification.getType()));
      else tellClient(s, 0);
    }
  }