Ejemplo n.º 1
0
 @SmallTest
 public void testValidSessionOtherWarmup() {
   mClientManager.recordUidHasCalledWarmup(mUid + 1);
   mClientManager.newSession(mCallback, mUid, null);
   assertEquals(
       ClientManager.SESSION_NO_WARMUP_ALREADY_CALLED, mClientManager.getWarmupState(mSession));
 }
Ejemplo n.º 2
0
  @SmallTest
  public void testValidSessionWarmupSeveralCalls() {
    mClientManager.recordUidHasCalledWarmup(mUid);
    mClientManager.newSession(mCallback, mUid, null);
    assertEquals(ClientManager.SESSION_WARMUP, mClientManager.getWarmupState(mSession));

    ICustomTabsCallback callback = new CustomTabsTestUtils.DummyCallback();
    IBinder session = callback.asBinder();
    mClientManager.newSession(callback, mUid, null);
    assertEquals(ClientManager.SESSION_WARMUP, mClientManager.getWarmupState(session));
  }
  /** {@inheritDoc} */
  @Override
  public void update(String key, String msg) {
    if (key.startsWith(Definitions.PREFIX_SENSORS_VISIBILITY)) {
      // notify all clients
      log.trace("a sensor has become (in)visible");
      String sensorId = key.replace(VISIBILITY, "");
      String msgToSend = null;
      if ("true".equals(msg)) {
        // for a visible message, we need all the sensors information
        Sensor s = Server.getSensorStorage().getSensorById(sensorId);
        if (s != null) {
          msgToSend =
              ServerProtocolAbstractor.createSensorVisibilityMessage(
                  sensorId, s.description, s.dataType, true);
          broadcastToAllClients(msgToSend);
          // create the visibility conf item for the admin clients:
          String confMsg = createSensorVisiblityConf(s);
          List<ServerClient> admins = null;
          synchronized (m_adminClients) {
            // copy to be thread-safe
            admins = new ArrayList<ServerClient>(m_adminClients.values());
          }
          sendToClients(admins, confMsg);

          // if its a polling sensor, we additionally need the polltime config:
          if (s.isPolling) {
            confMsg = createSensorPollTimeConf(s);
            sendToClients(admins, confMsg);
          }
        } else {
          log.warn("we got info about new sensor which isn't really there! id=" + sensorId);
        }
      } else {
        // sensor became invisble, we only need his id
        msgToSend =
            ServerProtocolAbstractor.createSensorVisibilityMessage(
                sensorId, "NOT_USED", "NOT_USED", false);
        broadcastToAllClients(msgToSend);
        // and unsubscribe all clients that might currently be subscribed:
        List<ServerClient> targets = null;
        synchronized (m_clients) {
          List<ServerClient> clients = m_clients.getClientsForSensor(sensorId);
          if (clients != null) {
            targets = new ArrayList<ServerClient>(clients);
          }
        }
        if (targets != null) {
          for (ServerClient unregMe : targets) {
            m_clients.onClientUnregistersForSensor(unregMe, sensorId);
          }
        }
      }
    }
  }
 /** {@inheritDoc} */
 @Override
 public void onClientDisconnectes(Client data) {
   ServerClient sc = m_clients.getServerClientByClientInfo(data);
   if (sc != null) {
     synchronized (m_clients) {
       m_clients.removeClient(sc);
     }
     sc.tryClose();
   } else {
     // log.warn("cannot find client " + data.m_id);
   }
 }
  /** {@inheritDoc} */
  @Override
  public void onRegisterForSensor(Client c, String sensorId, boolean status) {
    ServerClient sc = m_clients.getServerClientByClientInfo(c);
    if (sc == null) {
      log.warn("cannot find client! " + c.m_id);
      return;
    }

    if (status) {
      m_clients.onClientRegisteresForSensor(sc, sensorId);
    } else {
      m_clients.onClientUnregistersForSensor(sc, sensorId);
    }
  }
 /** Die a horrible death. Cannot be restarted. */
 public synchronized void stopRunning() {
   if (_dead) return;
   if (_context.router().isAlive() && _log.shouldLog(Log.WARN))
     _log.warn(
         "Stop the I2CP connection!  current leaseSet: " + _currentLeaseSet,
         new Exception("Stop client connection"));
   _dead = true;
   // we need these keys to unpublish the leaseSet
   if (_reader != null) _reader.stopReading();
   if (_writer != null) _writer.stopWriting();
   if (_socket != null)
     try {
       _socket.close();
     } catch (IOException ioe) {
     }
   _messages.clear();
   _acceptedPending.clear();
   if (_sessionKeyManager != null) _sessionKeyManager.shutdown();
   _manager.unregisterConnection(this);
   if (_currentLeaseSet != null) _context.netDb().unpublish(_currentLeaseSet);
   _leaseRequest = null;
   synchronized (_alreadyProcessed) {
     _alreadyProcessed.clear();
   }
   // _config = null;
   // _manager = null;
 }
  /**
   * Distribute the message. If the dest is local, it blocks until its passed to the target
   * ClientConnectionRunner (which then fires it into a MessageReceivedJob). If the dest is remote,
   * it blocks until it is added into the ClientMessagePool
   */
  MessageId distributeMessage(SendMessageMessage message) {
    Payload payload = message.getPayload();
    Destination dest = message.getDestination();
    MessageId id = new MessageId();
    id.setMessageId(getNextMessageId());
    long expiration = 0;
    int flags = 0;
    if (message.getType() == SendMessageExpiresMessage.MESSAGE_TYPE) {
      SendMessageExpiresMessage msg = (SendMessageExpiresMessage) message;
      expiration = msg.getExpirationTime();
      flags = msg.getFlags();
    }
    if (message.getNonce() != 0 && !_dontSendMSM) _acceptedPending.add(id);

    if (_log.shouldLog(Log.DEBUG))
      _log.debug(
          "** Receiving message "
              + id.getMessageId()
              + " with payload of size "
              + payload.getSize()
              + " for session "
              + _sessionId.getSessionId());
    // long beforeDistribute = _context.clock().now();
    // the following blocks as described above
    SessionConfig cfg = _config;
    if (cfg != null)
      _manager.distributeMessage(cfg.getDestination(), dest, payload, id, expiration, flags);
    // else log error?
    // long timeToDistribute = _context.clock().now() - beforeDistribute;
    // if (_log.shouldLog(Log.DEBUG))
    //    _log.warn("Time to distribute in the manager to "
    //              + dest.calculateHash().toBase64() + ": "
    //              + timeToDistribute);
    return id;
  }
Ejemplo n.º 8
0
  public void run() {
    log.warn(Messages.RESTART_HUB);

    BanList.First = null;
    ClientManager.getInstance().removeAllClients();

    Server.shutdown();
    System.gc(); // calling garbage collectors
    Main.Server = new HubServer();
    Main.curtime = System.currentTimeMillis();
    Main.Proppies = System.getProperties();
  }
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
   if (requestCode == RQ_CONNECT_DEVICE) {
     if (resultCode == Activity.RESULT_OK) {
       String address = data.getExtras().getString("device_address");
       clientManager.connect(btAdapter.getRemoteDevice(address));
     }
   } else if (requestCode == RQ_ENABLE_BT) {
     if (resultCode != Activity.RESULT_OK) {
       android.util.Log.e("", "Bluetoothが有効ではありません");
     }
   }
 }
 public void sendSound(View view) {
   try {
     switch (view.getId()) {
       case R.id.C:
         clientManager.write("c".getBytes());
         break;
       case R.id.D:
         clientManager.write("d".getBytes());
         break;
       case R.id.E:
         clientManager.write("e".getBytes());
         break;
       case R.id.F:
         clientManager.write("f".getBytes());
         break;
       case R.id.G:
         clientManager.write("g".getBytes());
         break;
     }
   } catch (Exception e) {
   }
 }
 @Override
 public void onClientRegistrationChanged(Client c, boolean registered) {
   List<Client> admins = null;
   // copy to avoid threading problems
   synchronized (m_adminClients) {
     admins = new ArrayList<Client>(m_adminClients.keySet());
   }
   String msg =
       AdminServerProtocolAbstractor.createClientMessage(c.m_id, c.m_address, registered);
   // send the client-change to every admin client
   for (Client admin : admins) {
     sendToClient(m_clients.getServerClientByClientInfo(admin), msg);
   }
 }
  /**
   * triggered when an admin client connects
   *
   * @param data
   * @param connection
   */
  public void onNewAdminClient(Client data, NetworkServiceClient connection) {
    // also trigger the normal client handling
    onNewClient(data, connection);

    ServerClient newAdminClient = new ServerClient(data, connection);
    synchronized (m_adminClients) {
      m_adminClients.put(data, newAdminClient);
    }

    // tell him about all the server configs + send him list of all clients
    List<ServerClient> all = null;
    synchronized (m_clients) {
      // copy the entries to be reistent to modifications while sending
      List<ServerClient> targets = m_clients.getAllClients();
      all = new ArrayList<ServerClient>(targets);
    }

    String msg = "";
    // tell him about all the clients that are connected
    for (ServerClient sc : all) {
      msg =
          AdminServerProtocolAbstractor.createClientMessage(
              sc.getClientInfo().m_id, sc.getClientInfo().m_address, true);
      sendToClient(newAdminClient, msg);
    }

    // tell him about all server configs:
    // TODO maybe add more configs!
    String pollTimeKey = Definitions.PREFIX_SERVER_DEFAULT_POLLING;
    String pollTimeValue = m_prefs.getValue(pollTimeKey);
    msg =
        AdminServerProtocolAbstractor.createConfigMessage(
            new Configuration(
                "default polling time: ", pollTimeKey, SettingType.number, pollTimeValue));
    sendToClient(newAdminClient, msg);

    // send all invisible sensors as sensor-config items
    // + send all polling sensors as polling frequency objects
    List<Sensor> allSensors = Server.getSensorStorage().getAllSensors();
    for (Sensor sensor : allSensors) {
      msg = createSensorVisiblityConf(sensor);
      sendToClient(newAdminClient, msg);
      if (sensor.isPolling) {
        msg = createSensorPollTimeConf(sensor);
        sendToClient(newAdminClient, msg);
      }
    }
  }
  /** {@inheritDoc} */
  @Override
  public void onNewClient(Client data, NetworkServiceClient connection) {
    ServerClient sc = new ServerClient(data, connection);
    m_clients.addClient(sc);

    List<Sensor> allSensors = Server.getSensorStorage().getAllSensors();

    for (Sensor sensor : allSensors) {
      String value = m_prefs.getValue(VISIBILITY + sensor.ident);
      if ("true".equals(value)) {
        String msg =
            ServerProtocolAbstractor.createSensorVisibilityMessage(
                sensor.ident, sensor.description, sensor.dataType, true);
        sendToClient(sc, msg);
      }
    }
  }
  protected void broadcastToAllClients(String msg) {
    // TODO: implement broadcasting, consider the following:
    // don't block the caller, because this could take some time
    // are clients where we lose the connection already handled?

    // XXX this dummy implementation BLOCKS THE WHOLE TIME!!!
    List<ServerClient> all = null;
    synchronized (m_clients) {
      // copy the entries to be reistent to modifications while sending
      List<ServerClient> targets = m_clients.getAllClients();
      all = new ArrayList<ServerClient>(targets);
    }

    if (log.isTraceEnabled()) {
      log.trace("sending to all " + all.size() + "clients");
    }
    for (ServerClient sc : all) {
      sendToClient(sc, msg);
    }
  }
  @Override
  public void onSensorDataReceived(Sensor s) {
    ArrayList<ServerClient> targets = null;
    synchronized (m_clients) {
      // copy the entries to be reistent to modifications while sending
      List<ServerClient> clients = m_clients.getClientsForSensor(s.ident);
      if (clients != null) {
        targets = new ArrayList<ServerClient>(clients);
      }
    }

    if (targets != null && targets.size() > 0) {
      log.trace(
          "broadcasting new sensor data from " + s.ident + " to " + targets.size() + " clients");
      String msgToSend = ServerProtocolAbstractor.createSensorDataMessage(s.ident, s.data);
      sendToClients(targets, msgToSend);
    } else {
      log.trace("broadcasting new sensor data from " + s.ident + " to 0 clients");
    }
  }
Ejemplo n.º 16
0
 void sessionEstablished(SessionConfig config) {
   _destHashCache = config.getDestination().calculateHash();
   if (_log.shouldLog(Log.DEBUG))
     _log.debug("SessionEstablished called for destination " + _destHashCache.toBase64());
   _config = config;
   // We process a few options here, but most are handled by the tunnel manager.
   // The ones here can't be changed later.
   Properties opts = config.getOptions();
   if (opts != null) {
     _dontSendMSM =
         "none".equals(opts.getProperty(I2PClient.PROP_RELIABILITY, "").toLowerCase(Locale.US));
     _dontSendMSMOnReceive = Boolean.parseBoolean(opts.getProperty(I2PClient.PROP_FAST_RECEIVE));
   }
   // per-destination session key manager to prevent rather easy correlation
   if (_sessionKeyManager == null) {
     int tags = TransientSessionKeyManager.DEFAULT_TAGS;
     int thresh = TransientSessionKeyManager.LOW_THRESHOLD;
     if (opts != null) {
       String ptags = opts.getProperty(PROP_TAGS);
       if (ptags != null) {
         try {
           tags = Integer.parseInt(ptags);
         } catch (NumberFormatException nfe) {
         }
       }
       String pthresh = opts.getProperty(PROP_THRESH);
       if (pthresh != null) {
         try {
           thresh = Integer.parseInt(pthresh);
         } catch (NumberFormatException nfe) {
         }
       }
     }
     _sessionKeyManager = new TransientSessionKeyManager(_context, tags, thresh);
   } else {
     _log.error(
         "SessionEstablished called for twice for destination "
             + _destHashCache.toBase64().substring(0, 4));
   }
   _manager.destinationEstablished(this);
 }
 public void disconnectDevice(View view) {
   clientManager.stop();
 }
 /**
  * get the number of connected clients, for status tracking
  *
  * @return
  */
 public int getClientCount() {
   return m_clients.getAllClients().size();
 }
Ejemplo n.º 19
0
  public void run() {
    queryMix = new CompiledQueryMix(maxQuery);
    while (!Thread.interrupted()) {
      boolean inWarmup;
      boolean inRun;
      boolean gotNew;
      synchronized (manager) {
        gotNew = pool.getNextQueryMix(queryMix);
        inWarmup = manager.isWarmupPhase();
        inRun = manager.isRunPhase();
      }

      if (interrupted()) {
        System.err.println("Thread interrupted. Quitting...");
        return;
      }
      // Either the warmup querymixes or the run querymixes ended
      if (!gotNew) {
        try {
          if (inWarmup) {
            // finish work for warmup
            if (!finishedWarmup) {
              manager.finishWarmup(this);
              finishedWarmup = true;
            }
            sleep(20); // still warmup, but no querymix, so wait and try again

            continue;
          } else if (!inRun) {
            sleep(20); // Run phase didn't start yet, so sleep
            continue;
          } else { // The run ended, report results, if there are any
            manager.finishRun(this);
            return; // And end Thread
          }
        } catch (InterruptedException e) {
          System.err.println("Thread interrupted. Quitting...");
          conn.close();
          return;
        }
      } else { // else run the Querymix
        Long startTime = System.nanoTime();
        while (queryMix.hasNext()) {
          CompiledQuery next = queryMix.getNext();
          if (manager.ignoreQueries[next.getNr() - 1]) queryMix.setCurrent(0, -1.0);
          else {
            conn.executeQuery(next, queryMix);
          }
        }
        System.out.println(
            "Thread "
                + nr
                + ": query mix "
                + queryMix.getRun()
                + ": "
                + String.format(Locale.US, "%.2f", queryMix.getQueryMixRuntime() * 1000)
                + "ms, total: "
                + String.format(
                    Locale.US, "%.2f", (System.nanoTime() - startTime) / (double) 1000000)
                + "ms");

        queryMix.finishRun();
      }
    }
  }
Ejemplo n.º 20
0
 @SmallTest
 public void testValidSessionNoWarmup() {
   mClientManager.newSession(mCallback, mUid, null);
   assertEquals(
       ClientManager.SESSION_NO_WARMUP_NOT_CALLED, mClientManager.getWarmupState(mSession));
 }
Ejemplo n.º 21
0
 @SmallTest
 public void testInvalidSessionWarmup() {
   mClientManager.recordUidHasCalledWarmup(mUid);
   assertEquals(ClientManager.NO_SESSION_WARMUP, mClientManager.getWarmupState(mSession));
 }
Ejemplo n.º 22
0
 @Override
 public void onPause() {
   super.onPause();
   ClientManager.get(getActivity()).saveClients();
 }
Ejemplo n.º 23
0
 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   mClientId = UUID.fromString(getArguments().getSerializable(EXTRA_CLIENT_ID).toString());
   mClient = ClientManager.get(getActivity()).getClient(mClientId);
 }
Ejemplo n.º 24
0
 @SmallTest
 public void testInvalidSessionNoWarmup() {
   assertEquals(ClientManager.NO_SESSION_NO_WARMUP, mClientManager.getWarmupState(mSession));
 }
Ejemplo n.º 25
0
 @SmallTest
 public void testValidSessionWarmup() {
   mClientManager.recordUidHasCalledWarmup(mUid);
   mClientManager.newSession(mCallback, mUid, null);
   assertEquals(ClientManager.SESSION_WARMUP, mClientManager.getWarmupState(mSession));
 }