コード例 #1
1
ファイル: Dashutil.java プロジェクト: vikrampatange/Nice-A
 /**
  * Starts a native process on the server
  *
  * @param command the command to start the process
  * @param dir the dir in which the process starts
  */
 static String startProcess(String command, String dir) throws IOException {
   StringBuffer ret = new StringBuffer();
   String[] comm = new String[3];
   comm[0] = COMMAND_INTERPRETER[0];
   comm[1] = COMMAND_INTERPRETER[1];
   comm[2] = command;
   long start = System.currentTimeMillis();
   try {
     // Start process
     Process ls_proc = Runtime.getRuntime().exec(comm, null, new File(dir));
     // Get input and error streams
     BufferedInputStream ls_in = new BufferedInputStream(ls_proc.getInputStream());
     BufferedInputStream ls_err = new BufferedInputStream(ls_proc.getErrorStream());
     boolean end = false;
     while (!end) {
       int c = 0;
       while ((ls_err.available() > 0) && (++c <= 1000)) {
         ret.append(conv2Html(ls_err.read()));
       }
       c = 0;
       while ((ls_in.available() > 0) && (++c <= 1000)) {
         ret.append(conv2Html(ls_in.read()));
       }
       try {
         ls_proc.exitValue();
         // if the process has not finished, an exception is thrown
         // else
         while (ls_err.available() > 0) ret.append(conv2Html(ls_err.read()));
         while (ls_in.available() > 0) ret.append(conv2Html(ls_in.read()));
         end = true;
       } catch (IllegalThreadStateException ex) {
         // Process is running
       }
       // The process is not allowed to run longer than given time.
       if (System.currentTimeMillis() - start > MAX_PROCESS_RUNNING_TIME) {
         ls_proc.destroy();
         end = true;
         ret.append("!!!! Process has timed out, destroyed !!!!!");
       }
       try {
         Thread.sleep(50);
       } catch (InterruptedException ie) {
       }
     }
   } catch (IOException e) {
     ret.append("Error: " + e);
   }
   return ret.toString();
 }
コード例 #2
1
  /**
   * Keep track, collect and update the stats of all the <tt>MediaStreamStats</tt> this
   * <tt>HammerStats</tt> handles.
   *
   * <p>Also write the results in the stats files.
   */
  public void run() {
    PrintWriter writer = null;
    StringBuilder allBldr = new StringBuilder();
    String delim;
    String delim_ = "";
    synchronized (this) {
      threadStop = false;
    }

    logger.info("Running the main loop");
    System.out.println("Inside HammerStats run method.\n");

    while (!threadStop) {
      synchronized (this) {
        if (overallStatsLogging || allStatsLogging || summaryStatsLogging) {
          if (allStatsLogging || summaryStatsLogging) {
            if (writer == null) {
              try {
                writer = new PrintWriter(allStatsFile, "UTF-8");
                writer.print("[\n");
              } catch (FileNotFoundException e) {
                logger.fatal("HammerStats stopping due to FileNotFound", e);
                stop();
              } catch (UnsupportedEncodingException e) {
                logger.fatal("HammerStats stopping due to " + "UnsupportedEncoding", e);
              }
            }

            // Clear the StringBuilder
            allBldr.setLength(0);

            writer.print(delim_ + '\n');
            delim_ = ",";
            writer.print("{\n");
            writer.print("  \"timestamp\":" + System.currentTimeMillis() + ",\n");
          }

          delim = "";
          logger.info("Updating the MediaStreamStats");
          for (FakeUserStats stats : fakeUserStatsList) {
            // We update the stats before using/reading them.
            stats.updateStats();
          }

          for (FakeUserStats stats : fakeUserStatsList) {
            if (allStatsLogging) {
              allBldr.append(delim + stats.getStatsJSON(2) + '\n');
              delim = ",";
            }

            if (summaryStatsLogging || overallStatsLogging) {
              logger.info(
                  "Adding stats values from the"
                      + " MediaStreamStats to their"
                      + " HammerSummaryStats objects");
              audioSummaryStats.add(stats.getMediaStreamStats(MediaType.AUDIO));
              videoSummaryStats.add(stats.getMediaStreamStats(MediaType.VIDEO));
            }
          }

          if (allStatsLogging) {
            logger.info("Writing all stats to file");
            writer.print("  \"users\":\n");
            writer.print("  [\n");
            writer.print(allBldr.toString());
            writer.print("  ]");
            if (summaryStatsLogging) writer.print(',');
            writer.print('\n');
          }
          if (summaryStatsLogging) {
            logger.info("Writing summary stats to file");
            writer.print("  \"summary\":\n");
            writer.print("  {\n");

            writer.print("    \"max\":\n");
            writer.print("    {\n");
            writer.print("        \"audio\":");
            writer.print(audioSummaryStats.getMaxJSON() + ",\n");
            writer.print("        \"video\":");
            writer.print(videoSummaryStats.getMaxJSON() + '\n');
            writer.print("    },\n");

            writer.print("    \"mean\":\n");
            writer.print("    {\n");
            writer.print("       \"audio\":");
            writer.print(audioSummaryStats.getMeanJSON() + ",\n");
            writer.print("        \"video\":");
            writer.print(videoSummaryStats.getMeanJSON() + '\n');
            writer.print("    },\n");

            writer.print("    \"min\":\n");
            writer.print("    {\n");
            writer.print("        \"audio\":");
            writer.print(audioSummaryStats.getMinJSON() + ",\n");
            writer.print("        \"video\":");
            writer.print(videoSummaryStats.getMinJSON() + '\n');
            writer.print("    },\n");

            writer.print("    \"standard_deviation\":\n");
            writer.print("    {\n");
            writer.print("        \"audio\":");
            writer.print(audioSummaryStats.getStandardDeviationJSON() + ",\n");
            writer.print("        \"video\":");
            writer.print(videoSummaryStats.getStandardDeviationJSON() + '\n');
            writer.print("    }\n");

            writer.print("  }\n");
          }
          if (allStatsLogging || summaryStatsLogging) {
            writer.append("}");
            writer.flush();
          }
        }

        if (summaryStatsLogging || overallStatsLogging) {
          logger.info(
              "Clearing the HammerSummaryStats by creating new"
                  + " SummaryStats objects for each watched stats");
          audioSummaryStats.clear();
          videoSummaryStats.clear();
        }
      }

      try {
        Thread.sleep(timeBetweenUpdate * 1000);
      } catch (InterruptedException e) {
        logger.fatal("Error during sleep in main loop : " + e);
        stop();
      }
    }
    logger.info("Exiting the main loop");

    if (writer != null) {
      writer.print("]\n");
      writer.close();
    }

    if (overallStatsLogging) writeOverallStats();
  }
コード例 #3
0
ファイル: krypton_api.java プロジェクト: 0ldMaid/Krypton
  public String delete_all_nodes() {

    System.out.println("Delete all nodes");

    while (network.database_in_use == 1) {

      int test_db = 0;
      System.out.println("Database in use... delete all nodes");
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
      }
      test_db++;
    } // *********************************

    mining.mining3 = false;

    krypton_database_delete_network pxd = new krypton_database_delete_network();

    krypton_database_load_network nodesx = new krypton_database_load_network();

    krypton_database_load loadx = new krypton_database_load();

    mining.mining3 = true;

    return "deleted";
  } // **********************
コード例 #4
0
ファイル: krypton_api.java プロジェクト: 0ldMaid/Krypton
  public String set_old_key(String keyx) {

    System.out.println("Build old keys");

    while (network.database_in_use == 1) {

      int test_db = 0;
      System.out.println("Database in use... import key");
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
      }
      test_db++;
    } // *********************************

    mining.mining3 = false;

    krypton_database_import_keys import_kx = new krypton_database_import_keys(keyx);

    krypton_database_load_network xxn = new krypton_database_load_network();
    krypton_database_load xxs = new krypton_database_load();

    mining.mining3 = true;

    return network.settingsx[5];
  } // **********************
コード例 #5
0
ファイル: krypton_api.java プロジェクト: 0ldMaid/Krypton
  public String set_new_node(String nodex) {

    System.out.println("Add new node");

    while (network.database_in_use == 1) {

      int test_db = 0;
      System.out.println("Database in use... import node");
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
      }
      test_db++;
    } // *********************************

    mining.mining3 = false;

    krypton_database_nodes add_node = new krypton_database_nodes(nodex);

    krypton_database_load_network nodesx = new krypton_database_load_network();

    krypton_database_load loadx = new krypton_database_load();

    mining.mining3 = true;

    return Integer.toString(network.network_list.size());
  } // **********************
コード例 #6
0
  /**
   * This is called when JPM runs in the background to start jobs
   *
   * @throws Exception
   */
  public void daemon() throws Exception {
    Runtime.getRuntime()
        .addShutdownHook(
            new Thread("Daemon shutdown") {
              public void run() {

                for (Service service : startedByDaemon) {
                  try {
                    reporter.error("Stopping " + service);
                    service.stop();
                    reporter.error("Stopped " + service);
                  } catch (Exception e) {
                    // Ignore
                  }
                }
              }
            });
    List<ServiceData> services = getServices();
    Map<String, ServiceData> map = new HashMap<String, ServiceData>();
    for (ServiceData d : services) {
      map.put(d.name, d);
    }
    List<ServiceData> start = new ArrayList<ServiceData>();
    Set<ServiceData> set = new HashSet<ServiceData>();
    for (ServiceData sd : services) {
      checkStartup(map, start, sd, set);
    }

    if (start.isEmpty()) reporter.warning("No services to start");

    for (ServiceData sd : start) {
      try {
        Service service = getService(sd.name);
        reporter.trace("Starting " + service);
        String result = service.start();
        if (result != null) reporter.error("Started error " + result);
        else startedByDaemon.add(service);
        reporter.trace("Started " + service);
      } catch (Exception e) {
        reporter.error("Cannot start daemon %s, due to %s", sd.name, e);
      }
    }

    while (true) {
      for (Service sd : startedByDaemon) {
        try {
          if (!sd.isRunning()) {
            reporter.error("Starting due to failure " + sd);
            String result = sd.start();
            if (result != null) reporter.error("Started error " + result);
          }
        } catch (Exception e) {
          reporter.error("Cannot start daemon %s, due to %s", sd, e);
        }
      }
      Thread.sleep(10000);
    }
  }
コード例 #7
0
 public void run() {
   while (true) {
     try {
       repaint();
       Thread.sleep(1);
     } catch (Throwable e) {
     }
   }
 }
コード例 #8
0
ファイル: DrawTool.java プロジェクト: tstamler/linAlg
 static String waitForInputString() {
   try {
     while (!hasEntered) {
       Thread.sleep(100);
     }
     return inputField.getText();
   } catch (Exception e) {
     return "";
   }
 }
コード例 #9
0
 /**
  * Method to replay the frames (pictures) added so far
  *
  * @param sleepTime the amount to sleep in milliseconds between frames
  */
 public void replay(int sleepTime) {
   Picture picture = null;
   Iterator iterator = pictureList.iterator();
   while (iterator.hasNext()) {
     picture = (Picture) iterator.next();
     pictureFrame.setPicture(picture);
     try {
       Thread.sleep(sleepTime);
     } catch (Exception ex) {
     }
   }
 }
コード例 #10
0
ファイル: krypton_api.java プロジェクト: 0ldMaid/Krypton
  public String set_new_block(String array) {

    String jsontext = new String("");

    String update_token[] = new String[network.listing_size];

    try {

      JSONParser parserx = new JSONParser();
      Object objx = parserx.parse(array);
      JSONObject jsonObjectx = (JSONObject) objx;

      for (int loop = 0; loop < network.listing_size; loop++) { // ************

        update_token[loop] = (String) jsonObjectx.get(Integer.toString(loop));
        System.out.println("import " + update_token[loop]);
      } // *******************************************************************

    } catch (Exception e) {
      e.printStackTrace();
    }

    String testerx = new String("error");

    for (int loop = 0; loop < network.listing_size; loop++) { // ************
      try {
        if (update_token[loop].equals("0")) {}
      } catch (Exception e) {
        statex = "0";
        testerx = "1";
        jsontext = "e09 NullException";
      }
    } // *******************************************************************

    while (!testerx.equals("1")) {

      System.out.println("Mining send new block update >>>>");

      // String testg = krypton_net_client.send_new_block_update(update_token);
      // System.out.println("testg " + testg);

      // if(testg.equals("1") || testg.equals("0")){System.out.println("BREAK"); break;}

      try {
        Thread.sleep(10000);
      } catch (InterruptedException e) {
      }
    } // while

    return jsontext;
  } // ***************************************
コード例 #11
0
ファイル: move.java プロジェクト: EdvardPedersen/GeStore
  private static String lock(String lock) {
    String realPath = "";
    String parent = "/lock";
    String lockName = parent + "/" + lock;

    logger.debug("Getting lock " + lockName);

    try {
      if (zkInstance.exists(parent, false) == null)
        zkInstance.create(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.fromFlag(0));
    } catch (Exception E) {
      logger.error("Error creating lock node: " + E.toString());
      return null;
    }

    List<String> children = new LinkedList<String>();
    try {
      // List <ACL> ACLList = zkInstance.getACL(lockName, zkInstance.exists(lock, false));

      realPath =
          zkInstance.create(
              lockName, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
      // children = zkInstance.getChildren(realPath, false);
      checkLock:
      while (true) {
        children = zkInstance.getChildren(parent, false);
        for (String curChild : children) {
          String child = parent + "/" + curChild;
          // System.out.println(child + " " + realPath + " " +
          // Integer.toString(child.compareTo(realPath)));
          if (child.compareTo(realPath) < 0
              && child.length() == realPath.length()
              && curChild.startsWith(lock)) {
            // System.out.println(child + " cmp to " + realPath);
            Thread.sleep(300);
            continue checkLock;
          }
        }
        logger.info("Got lock " + lockName);
        return realPath;
      }
    } catch (Exception E) {
      logger.error("Exception while trying to get lock " + lockName + " :" + E.toString());
      E.printStackTrace();
      return null;
    }
  }
コード例 #12
0
  public void run() {
    // ///////////////////////////
    Gateway.addLiveThread(this);
    // ///////////////////////////
    while (Gateway.running) {
      try {
        pdud = (PDUData) fromSMSC.dequeue(); // blocks until having
        // an item
        // pdu = (PDU) fromSMSC.dequeue(); //blocks until having an item
        pdu = (PDU) pdud.getPDU();
        if (pdu.isRequest()) {
          this.RequestID = pdud.getRequestID();
          processRequest(pdu);
        }
      } catch (DBException ex) { // when lost connection to db
        Logger.error(this.getClass().getName(), "DBException: " + ex.getMessage());
        DBTools.ALERT(
            "RequestProcessor",
            "RequestProcessor",
            Constants.ALERT_WARN,
            Preference.Channel + "DBException: " + ex.getMessage(),
            Preference.ALERT_CONTACT);
        Logger.error(this.getClass().getName(), "Alert2YM DBException: " + ex.getMessage());
      } catch (Exception e) {
        Logger.error(this.getClass().getName(), "Exception: " + e.getMessage());

        DBTools.ALERT(
            "RequestProcessor",
            "RequestProcessor",
            Constants.ALERT_WARN,
            Preference.Channel + "Exception: " + e.getMessage(),
            Preference.ALERT_CONTACT);
      }

      try {
        Thread.sleep(50);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    // /////////////////////////////
    Logger.info(this.getClass().getName(), "{" + this.getClass().getName() + " stopped}");
    this.destroy();
    // /////////////////////////////
  }
コード例 #13
0
 public void run() {
   System.out.println("ReminderServiceOld: Starting at " + new Date());
   while (!l.isEmpty()) {
     Date d = new Date();
     Item i = (Item) l.get(0);
     long interval = i.due.getTime() - d.getTime();
     if (interval > 0) {
       System.out.println("Sleeping until " + i.due);
       try {
         Thread.sleep(interval);
       } catch (InterruptedException e) {
         System.exit(1); // unexpected intr
       }
       message(i.due + ": " + i.message);
     } else message("MISSED " + i.message + " at " + i.due);
     l.remove(0);
   }
   System.exit(0);
 }
コード例 #14
0
ファイル: krypton_api.java プロジェクト: 0ldMaid/Krypton
  public String build_keysx() {

    System.out.println("Build new keys");

    while (network.database_in_use == 1) {

      int test_db = 0;
      System.out.println("Database in use...keys");
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
      }
      test_db++;
    } // *********************************

    krypton_rebuild_keys keysx = new krypton_rebuild_keys();
    krypton_database_load loadxs = new krypton_database_load();

    return network.settingsx[5];
  } // **********************
コード例 #15
0
ファイル: DrawTool.java プロジェクト: tstamler/linAlg
 public static void animationPause(int pauseTime) {
   if ((pauseTime < 1) || (pauseTime > 1000)) {
     pauseTime = 100;
   }
   try {
     Thread.sleep(pauseTime);
     synchronized (animPoints) {
       animPoints.clear();
     }
     synchronized (animLines) {
       animLines.clear();
     }
     synchronized (animOvals) {
       animOvals.clear();
     }
     synchronized (animRectangles) {
       animRectangles.clear();
     }
   } catch (InterruptedException e) {
   }
 }
コード例 #16
0
  public void onCreate() {
    int flags, screenLightVal = 1;
    Sensor mSensor;
    List<Sensor> sensors;

    if (scanData == null) return; // no ScanData, not possible to run correctly...

    PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
    SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    try {
      screenLightVal = Integer.parseInt(SP.getString("screenLight", "2"));
    } catch (NumberFormatException nfe) {
    }
    if (screenLightVal == 1) flags = PowerManager.PARTIAL_WAKE_LOCK;
    else if (screenLightVal == 3) flags = PowerManager.FULL_WAKE_LOCK;
    else flags = PowerManager.SCREEN_DIM_WAKE_LOCK;
    wl = pm.newWakeLock(flags, "OpenWLANMap");
    wl.acquire();
    while (myWLocate == null) {
      try {
        myWLocate = new MyWLocate(this);
        break;
      } catch (IllegalArgumentException iae) {
        myWLocate = null;
      }
      try {
        Thread.sleep(100);
      } catch (InterruptedException ie) {
      }
    }

    try {
      scanData.setUploadThres(Integer.parseInt(SP.getString("autoUpload", "0")));
    } catch (NumberFormatException nfe) {
    }
    try {
      scanData.setNoGPSExitInterval(
          Integer.parseInt(SP.getString("noGPSExitInterval", "0")) * 60 * 1000);
    } catch (NumberFormatException nfe) {
    }

    Intent intent = new Intent(this, OWMapAtAndroid.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0);

    notification =
        new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.icon)
            .setContentTitle(getResources().getText(R.string.app_name))
            .setContentText("")
            .setContentIntent(pendIntent)
            .build();

    notification.flags |= Notification.FLAG_NO_CLEAR;
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    startForeground(1703, notification);

    getScanData().setService(this);
    getScanData().setmView(new HUDView(this));
    getScanData().getmView().setValue(getScanData().incStoredValues());
    WindowManager.LayoutParams params =
        new WindowManager.LayoutParams(
            WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
            WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT);
    params.gravity = Gravity.LEFT | Gravity.BOTTOM;
    params.setTitle("Load Average");
    WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
    wm.addView(getScanData().getmView(), params);

    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

    sensorManager.registerListener(
        this,
        sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
        SensorManager.SENSOR_DELAY_GAME);
    sensorManager.registerListener(
        this,
        sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
        SensorManager.SENSOR_DELAY_GAME);
    sensors = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
    mSensor = sensors.get(0);
    getScanData().getTelemetryData().setAccelMax(mSensor.getMaximumRange());
    telemetryDir = Environment.getExternalStorageDirectory().getPath() + "/telemetry/";
    File dir = new File(telemetryDir);
    dir.mkdir();

    connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
  }
コード例 #17
0
  public void run() {
    int i,
        j,
        storedValues,
        sleepTime = 3000,
        timeoutCtr = 0,
        lastFlags = -1,
        trackCnt = 0,
        lastLocMethod = -5;
    String bssid;
    WMapEntry currEntry;
    DataOutputStream out;
    FileInputStream in;

    while (running) {
      try {
        if (scanData.getNoGPSExitInterval() > 0) {
          if (System.currentTimeMillis() > lastGPSTime + scanData.getNoGPSExitInterval()) {
            break;
          }
        }
        if (ScanService.scanData.getThreadMode() == OWMapAtAndroid.THREAD_MODE_UPLOAD) {
          if ((m_uploadThread != null) && (m_uploadThread.isUploading()))
            OWMapAtAndroid.sendMessage(
                ScannerHandler.MSG_SIMPLE_ALERT,
                0,
                0,
                getResources().getText(R.string.upload_in_progress));
          else m_uploadThread = new UploadThread(scanData, this, SP, false, notification, null);
          ScanService.scanData.setThreadMode(OWMapAtAndroid.THREAD_MODE_SCAN);
        } else {
          if ((posState == 0) && (scanData != null) && (scanData.isScanningEnabled())) {
            posState = 1;
            timeoutCtr = 0;
            if (scanData.getFlags() != lastFlags) {
              if ((scanData.getFlags() & OWMapAtAndroid.FLAG_NO_NET_ACCESS) == 0)
                scanData.getWifiManager().createWifiLock(WifiManager.WIFI_MODE_FULL, "OpenWLANMap");
              else
                scanData
                    .getWifiManager()
                    .createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, "OpenWLANMap");
              lastFlags = scanData.getFlags();
            }
            if ((scanData.getFlags() & OWMapAtAndroid.FLAG_NO_NET_ACCESS) == 0)
              myWLocate.wloc_request_position(WLocate.FLAG_NO_IP_LOCATION);
            else {
              myWLocate.wloc_request_position(
                  WLocate.FLAG_NO_NET_ACCESS | WLocate.FLAG_NO_IP_LOCATION);
              //                  stopGoogleLocation();
            }
          } else if (!scanData.isScanningEnabled()) {
            try {
              trackCnt += 1500;
              Thread.sleep(1500);
            } catch (InterruptedException ie) {

            }
          }
          if (posState == 1) {
            // sleep while waiting for result
            try {
              trackCnt += 2500;
              java.lang.Thread.sleep(2500); // is interrupted from result handler
              timeoutCtr++;
              if (timeoutCtr > 3) {
                timeoutCtr = 0;
                posState = 0;
              }
            } catch (InterruptedException ie) {
            }
          }
          if ((posState == 2) || (posState == 100)) {
            loc_info locationInfo;
            NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            locationInfo = myWLocate.last_location_info();
            if (lastLocMethod != locationInfo.lastLocMethod) {
              scanData.getmView().setMode(locationInfo.lastLocMethod);
              scanData.getmView().postInvalidate();
              lastLocMethod = locationInfo.lastLocMethod;
            }
            if (posState == 100) locationInfo.lastLocMethod = -1;
            OWMapAtAndroid.sendMessage(
                OWMapAtAndroid.ScannerHandler.MSG_UPD_LOC_STATE,
                (int) (lastRadius * 1000),
                locationInfo.lastLocMethod,
                locationInfo);

            if (SP.getBoolean("autoConnect", false)) {
              if (!mWifi.isConnected()) {
                for (i = 0; i < locationInfo.wifiScanResult.size(); i++) {
                  ScanResult result;

                  result = locationInfo.wifiScanResult.get(i);
                  result.capabilities = result.capabilities.toUpperCase(Locale.US);
                  if ((isFreeHotspot(result) & WMapEntry.FLAG_IS_FREIFUNK) != 0) {
                    // auto-connect to this open network

                    WifiConfiguration wifiConfig = new WifiConfiguration();
                    wifiConfig.BSSID = result.BSSID;
                    wifiConfig.priority = 1;
                    wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
                    wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                    wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                    wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                    wifiConfig.status = WifiConfiguration.Status.ENABLED;

                    int netId = scanData.getWifiManager().addNetwork(wifiConfig);
                    scanData.getWifiManager().enableNetwork(netId, true);
                  }
                }
              }
            }
            if ((posValid)
                && (locationInfo.wifiScanResult != null)
                && (locationInfo.wifiScanResult.size() > 0)) {
              boolean foundExisting;

              for (i = 0; i < locationInfo.wifiScanResult.size(); i++) {
                ScanResult result;

                result = locationInfo.wifiScanResult.get(i);
                bssid = result.BSSID.replace(":", "").replace(".", "").toUpperCase(Locale.US);
                if (bssid.equalsIgnoreCase("000000000000")) break;
                foundExisting = false;
                scanData.getLock().lock();
                for (j = 0; j < scanData.getWmapList().size(); j++) {
                  currEntry = scanData.getWmapList().elementAt(j);
                  if (currEntry.getBSSID().equalsIgnoreCase(bssid)) {
                    currEntry.setPos(lastLat, lastLon);
                    foundExisting = true;
                    break;
                  }
                }
                if (!foundExisting) {
                  String lowerSSID;

                  storedValues = scanData.incStoredValues();
                  scanData.getmView().setValue(storedValues);
                  scanData.getmView().postInvalidate();
                  currEntry = new WMapEntry(bssid, result.SSID, lastLat, lastLon, storedValues);
                  lowerSSID = result.SSID.toLowerCase(Locale.US);
                  if ((lowerSSID.endsWith("_nomap"))
                      || // Google unsubscibe option
                      (lowerSSID.contains("iphone"))
                      || // mobile AP
                      (lowerSSID.contains("android"))
                      || // mobile AP
                      (lowerSSID.contains("motorola"))
                      || // mobile AP
                      (lowerSSID.contains("deinbus.de"))
                      || // WLAN network on board of German bus
                      (lowerSSID.contains("fernbus"))
                      || // WLAN network on board of German bus
                      (lowerSSID.contains("flixbus"))
                      || // WLAN network on board of German bus
                      (lowerSSID.contains("ecolines"))
                      || // WLAN network on board of German bus
                      (lowerSSID.contains("eurolines_wifi"))
                      || // WLAN network on board of German bus
                      (lowerSSID.contains("contiki-wifi"))
                      || // WLAN network on board of bus
                      (lowerSSID.contains("guest@ms "))
                      || // WLAN network on Hurtigruten ships
                      (lowerSSID.contains("admin@ms "))
                      || // WLAN network on Hurtigruten ships
                      (lowerSSID.contains("nsb_interakti"))
                      || // WLAN network in NSB trains
                      (lowerSSID.equals("southwestwifi"))) // WLAN network on Southwest flights
                  currEntry.setFlags(currEntry.getFlags() | WMapEntry.FLAG_IS_NOMAP);
                  else currEntry.setFlags(currEntry.getFlags() | isFreeHotspot(result));
                  if (isFreeHotspot(currEntry.getFlags())) scanData.incFreeHotspotWLANs();
                  scanData.getWmapList().add(currEntry);
                  if ((scanData.getUploadThres() > 0)
                      && (storedValues > scanData.getUploadThres())) {
                    if ((m_uploadThread == null) || (!m_uploadThread.isUploading())) {
                      if (mWifi.isConnected()) {
                        m_uploadThread =
                            new UploadThread(scanData, this, SP, true, notification, mWifi);
                      }
                    }
                  }
                }
                result.capabilities = result.capabilities.toUpperCase(Locale.US);
                scanData.getLock().unlock();
              }
            }
            scanData.getLock().lock();
            for (j = 0; j < scanData.getWmapList().size(); j++) {
              currEntry = scanData.getWmapList().elementAt(j);
              if ((currEntry.getLastUpdate() + OWMapAtAndroid.RECV_TIMEOUT
                      < System.currentTimeMillis())
                  && ((currEntry.getFlags() & WMapEntry.FLAG_IS_VISIBLE) == 0)) {
                scanData.getWmapList().remove(j);
                if (currEntry.posIsValid()) {
                  int padBytes = 0, k;

                  try {
                    in = scanData.getCtx().openFileInput(OWMapAtAndroid.WSCAN_FILE);
                    padBytes = in.available() % 28;
                    in.close();
                    if (padBytes > 0) padBytes = 28 - padBytes;
                  } catch (IOException ioe) {
                    ioe.printStackTrace();
                  }
                  try {
                    out =
                        new DataOutputStream(
                            scanData
                                .getCtx()
                                .openFileOutput(
                                    OWMapAtAndroid.WSCAN_FILE,
                                    Context.MODE_PRIVATE | Context.MODE_APPEND));
                    if (padBytes > 0) for (k = 0; k < padBytes; k++) out.writeByte(0);
                    out.write(currEntry.getBSSID().getBytes(), 0, 12);
                    if ((currEntry.getFlags() & WMapEntry.FLAG_IS_NOMAP) != 0) {
                      out.writeDouble(0.0);
                      out.writeDouble(0.0);
                    } else {
                      out.writeDouble(currEntry.getLat());
                      out.writeDouble(currEntry.getLon());
                    }
                    out.close();
                  } catch (IOException ioe) {
                    ioe.printStackTrace();
                  }

                  if ((currEntry.getFlags()
                          & (WMapEntry.FLAG_IS_FREIFUNK | WMapEntry.FLAG_IS_NOMAP))
                      == WMapEntry.FLAG_IS_FREIFUNK) {
                    padBytes = 0;
                    try {
                      in = scanData.getCtx().openFileInput(OWMapAtAndroid.WFREI_FILE);
                      padBytes = in.available() % 12;
                      in.close();
                      if (padBytes > 0) padBytes = 12 - padBytes;
                    } catch (IOException ioe) {
                      ioe.printStackTrace();
                    }
                    try {
                      out =
                          new DataOutputStream(
                              scanData
                                  .getCtx()
                                  .openFileOutput(
                                      OWMapAtAndroid.WFREI_FILE,
                                      Context.MODE_PRIVATE | Context.MODE_APPEND));
                      if (padBytes > 0) for (k = 0; k < padBytes; k++) out.writeByte(0);
                      out.write(currEntry.getBSSID().getBytes(), 0, 12);
                      out.close();
                    } catch (IOException ioe) {
                      ioe.printStackTrace();
                    }
                  }
                }
              }
              //               flushData(false);
            }
            scanData.getLock().unlock();
            m_lastSpeed = locationInfo.lastSpeed;
            if (!SP.getBoolean("adaptiveScanning", true)) sleepTime = 500;
            else if (locationInfo.lastSpeed > 90) sleepTime = 350;
            else if (locationInfo.lastSpeed < 0)
              sleepTime = 1300; // no speed information, may be because of WLAN localisation
            else if (locationInfo.lastSpeed < 6) sleepTime = 2500; // user seems to walk
            else {
              double f;

              f = 1.0 - (locationInfo.lastSpeed / 90.0);
              sleepTime = (int) ((1000.0 * f) + 350);
            }

            try {
              trackCnt += sleepTime;
              java.lang.Thread.sleep(sleepTime); // sleep between scans
            } catch (InterruptedException ie) {

            }
            posState = 0;
          }
        }
      } catch (NullPointerException npe) // in case the parent activity dies too fast
      {
        npe.printStackTrace();
      }
      if ((trackCnt > 500000) && (lastLat != 0) && (lastLon != 0)) {
        if (SP.getBoolean("track", false)) new UploadPositionTask().execute(null, null, null);
        trackCnt = 0;
      }
    }
    onDestroy(); // remove all resources (in case the thread was stopped due to some other reason
  }
コード例 #18
0
ファイル: C1.java プロジェクト: guneetsinghmehta/CN_project
  public static void main(String args[]) throws InterruptedException, IOException {
    int i, j;
    String serverInetAddress = "localhost";

    String server1AddressString = "10.10.1.1";
    InetAddress server1Address = InetAddress.getByName(server1AddressString);
    String server2AddressString = "10.10.2.2";
    InetAddress server2Address = InetAddress.getByName(server2AddressString);
    String server3AddressString = "10.10.3.2";
    InetAddress server3Address = InetAddress.getByName(server3AddressString);
    String server4AddressString = "localhost";
    InetAddress server4Address = InetAddress.getByName(server4AddressString);

    DatagramSocket skt;
    {
      skt = new DatagramSocket(PORT_NUMBER_CLIENT); // socket used to listen and write
      InetAddress host = InetAddress.getByName(serverInetAddress);
      int serversocket = S1.PORT_NUMBER_SERVER;

      String msg = "Send file size";
      byte[] b = msg.getBytes();

      // dummy assignments - not used anywhere
      int filesize = 1;
      DatagramPacket reply, request;
      reply = new DatagramPacket(b, b.length, host, serversocket);
      request = new DatagramPacket(b, b.length, host, serversocket);

      for (i = 1; i <= 3; i++) {
        // defining a packet called request with parameters b(msg in bytes), b.length, host Internet
        // address and socket number
        if (i == 1) {
          host = server1Address;
        } else if (i == 2) {
          host = server2Address;
        } else if (i == 3) {
          host = server3Address;
        }
        request = new DatagramPacket(b, b.length, host, serversocket);
        // System.out.println("request sent from client to server");
        Thread.sleep(S1.PAUSE_DURATION); // for error checks

        // Sending the packet- for getting the file size
        skt.send(request);

        //		getting reply from
        // server........................................................................................
        byte[] buffer =
            new byte
                [S1.PACKET_SIZE]; // apparently the size of data packet at the receiving side needs
                                  // to be bigger than the size of incoming datapacket
        reply = new DatagramPacket(buffer, buffer.length);

        // receiving packet from server - contatining filesize
        skt.receive(reply);
        // System.out.println("Response Received from server");

        // System.out.println("on Client: - filesize= "+new String(reply.getData()));
        filesize = Integer.parseInt(new String(reply.getData()).trim());
        // System.out.println("on Client: - filesize= "+filesize);
        Thread.sleep(S1.PAUSE_DURATION);
      }

      // here the client know the size of the file
      // Find the number of times it must make iterations - dividing filesize by packet_size
      // Request that many packets from server
      String[] buffer_string = new String[BUFFER_SIZE_CLIENT];
      float delay[] = new float[filesize / S1.PACKET_SIZE];
      System.out.println(filesize);
      System.out.println(S1.PACKET_SIZE);
      System.out.println(filesize / S1.PACKET_SIZE);
      Thread.sleep(2000);
      byte[] buffer = new byte[S1.PACKET_SIZE];
      for (i = 0; i < filesize / S1.PACKET_SIZE; i++) {
        if (i % 100 != 0) {
          // System.out.print(" "+i);
        } else {
          System.out.println(" " + i);
        }

        msg = String.valueOf(i);
        b = msg.getBytes();

        if (i % 3 == 0) {
          host = server1Address;
        } else if (i % 3 == 1) {
          host = server2Address;
        } else if (i % 3 == 2) {
          host = server3Address;
        }

        request = new DatagramPacket(b, b.length, host, serversocket);

        skt.send(request);
        delay[i] = System.nanoTime();
        Thread.sleep(10);
        skt.receive(reply);
        delay[i] = System.nanoTime() - delay[i];
        delay[i] = delay[i] / (1000000);
        /*
        if(empty_index<BUFFER_SIZE_CLIENT)
        {
        	buffer_string[empty_index]=new String(reply.getData());
        	empty_index++;
        }
        else
        {
        	for(j=0;j<BUFFER_SIZE_CLIENT-1;j++)
        	{
        		buffer_string[j]=buffer_string[j+1];
        	}
        	buffer_string[BUFFER_SIZE_CLIENT-1]=new String(reply.getData());
        }*/

        // display_buffer(buffer_string);
      }
      Arrays.sort(delay);
      float delay2[] = new float[filesize / S1.PACKET_SIZE];
      for (i = 0; i < delay2.length; i++) {
        delay2[i] = delay[delay.length - i - 1];
      }
      // delay2 stores the array in descending values

      float[] Sk = new float[filesize / S1.PACKET_SIZE];
      Sk[0] = (float) 0.0;

      for (i = 1; i < filesize / S1.PACKET_SIZE; i++) {
        for (j = 1; j <= i; j++) {
          Sk[i] = Sk[i] + delay2[j];
        }
        Sk[i] = Sk[i] / (10 * i);
      }
      make_output(Sk);
      System.out.format(
          "Sk at 2=%f\n,10=%f\n,20=%f\n,100=%f\n and 30000=%f\n ",
          Sk[1], Sk[9], Sk[19], Sk[99], Sk[29999]);
      // display_buffer(buffer_string);
      skt.close();
    }
  }
コード例 #19
0
ファイル: krypton_api.java プロジェクト: 0ldMaid/Krypton
    public void
        run() { // ************************************************************************************

      String jsonText2 = new String("");

      JSONObject obj_out = new JSONObject();

      ServerSocket welcomeSocket;

      while (true) {

        try { // *********************************************************

          welcomeSocket = new ServerSocket(network.api_port, 0, InetAddress.getByName("localhost"));
          Socket connectionSocket = welcomeSocket.accept();
          BufferedReader inFromClient =
              new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
          DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
          clientSentence = inFromClient.readLine();

          JSONParser parser = new JSONParser();

          try { // *********************************************************

            statex = "0";
            responsex = "e00";
            jsonText = "";

            if (!clientSentence.contains("")) {
              throw new EmptyStackException();
            }
            Object obj = parser.parse(clientSentence);

            jsonObject = (JSONObject) obj;

            String request = (String) jsonObject.get("request");

            String item_id = new String("");
            String item_array = new String("");
            String old_key = new String("");
            String node = new String("");
            try {
              item_id = (String) jsonObject.get("item_id").toString();
            } catch (Exception e) {
              System.out.println("extra info no item_id...");
            }
            try {
              item_array = (String) jsonObject.get("item_array").toString();
            } catch (Exception e) {
              System.out.println("extra info no item_array...");
            }
            try {
              old_key = (String) jsonObject.get("key").toString();
            } catch (Exception e) {
              System.out.println("extra info no key...");
            }
            try {
              node = (String) jsonObject.get("node").toString();
            } catch (Exception e) {
              System.out.println("extra info no node...");
            }

            while (network.database_in_use == 1 && !request.equals("status")) {

              System.out.println("Database in use...");
              try {
                Thread.sleep(1000);
              } catch (InterruptedException e) {
              }
            } // **************************************************************

            if (request.equals("status")) {
              statex = "1";
              responsex = get_status();
            } // ***************************
            else if (request.equals("get_version")) {
              statex = "1";
              responsex = network.versionx;
            } //
            else if (request.equals("get_tor_active")) {
              statex = "1";
              responsex = Integer.toString(network.tor_active);
            } //
            else if (request.equals("get_last_block")) {
              statex = "1";
              responsex = network.last_block_id;
            } //
            else if (request.equals("get_last_block_timestamp")) {
              statex = "1";
              responsex = network.last_block_timestamp;
            } //
            else if (request.equals("get_last_block_hash")) {
              statex = "1";
              responsex = network.last_block_idx;
            } //
            else if (request.equals("get_difficulty")) {
              statex = "1";
              responsex = Long.toString(network.difficultyx);
            } //
            else if (request.equals("get_last_mining_id")) {
              statex = "1";
              responsex = network.last_block_mining_idx;
            } //
            else if (request.equals("get_prev_mining_id")) {
              statex = "1";
              responsex = network.prev_block_mining_idx;
            } //
            else if (request.equals("get_last_unconfirmed_id")) {
              statex = "1";
              responsex = get_item_ids();
            } //
            else if (request.equals("get_my_token_total")) {
              statex = "1";
              responsex = Integer.toString(network.database_listings_owner);
            } //
            else if (request.equals("get_my_id_list")) {
              statex = "1";
              responsex = get_item_ids();
            } //
            else if (request.equals("get_my_ids_limit")) {
              statex = "1";
              responsex = get_item_ids();
            } //
            else if (request.equals("get_token")) {
              statex = "1";
              responsex = get_item_array(item_id);
            } //
            else if (request.equals("get_settings")) {
              statex = "1";
              responsex = get_settings_array();
            } //
            else if (request.equals("get_mining_info")) {
              statex = "1";
              responsex = get_item_array(item_id);
            } //
            else if (request.equals("get_new_keys")) {
              statex = "1";
              responsex = build_keysx();
            } //
            else if (request.equals("delete_node")) {
              statex = "1";
              responsex = delete_node(node);
            } //
            else if (request.equals("delete_all_nodes")) {
              statex = "1";
              responsex = delete_all_nodes();
            } //
            else if (request.equals("set_new_node")) {
              statex = "1";
              responsex = set_new_node(node);
            } //
            else if (request.equals("set_old_key")) {
              statex = "1";
              responsex = set_old_key(old_key);
            } //
            else if (request.equals("set_new_block")) {
              statex = "1";
              responsex = set_new_block(item_array);
            } //
            else if (request.equals("set_edit_block")) {
              statex = "1";
              update_state = "set_edit_block";
              responsex = update_token(item_array);
            } //
            else if (request.equals("set_transfer_block")) {
              statex = "1";
              update_state = "set_transfer_block";
              responsex = update_token(item_array);
            } //
            else if (request.equals("system_restart")) {
              statex = "1";
              responsex = "restarting";
              toolkit = Toolkit.getDefaultToolkit();
              xtimerx = new Timer();
              xtimerx.schedule(new RemindTask_restart(), 0);
            } //
            else if (request.equals("system_exit")) {
              statex = "1";
              System.exit(0);
            } //
            else {
              statex = "0";
              responsex = "e01 UnknownRequestException";
            }

          } // try
          catch (ParseException e) {
            e.printStackTrace();
            statex = "0";
            responsex = "e02 ParseException";
          } catch (Exception e) {
            e.printStackTrace();
            statex = "0";
            responsex = "e03 Exception";
          }

          JSONObject obj = new JSONObject();
          obj.put("response", statex);
          try {
            obj.put("message", responsex);
          } catch (Exception e) {
            e.printStackTrace();
          }

          StringWriter outs = new StringWriter();
          obj.writeJSONString(outs);
          jsonText = outs.toString();
          System.out.println("SEND RESPONSE " + responsex);

          outToClient.writeBytes(jsonText + '\n');
          welcomeSocket.close();

        } catch (Exception e) {
          e.printStackTrace();
          System.out.println("Server ERROR x3");
        }
      } // **********while
    } // runx***************************************************************************************************
コード例 #20
0
ファイル: JCanvas.java プロジェクト: xaleth09/Connect4-AI
 public static void sleep(int ms) {
   try {
     Thread.sleep(ms);
   } catch (Exception e) {
   }
 }