/** Start the background thread. */
  public void start() {
    // create a random list of cities

    cities = new City[TravelingSalesman.CITY_COUNT];
    for (int i = 0; i < TravelingSalesman.CITY_COUNT; i++) {
      cities[i] =
          new City(
              (int) (Math.random() * (getBounds().width - 10)),
              (int) (Math.random() * (getBounds().height - 60)));
    }

    // create the initial chromosomes

    chromosomes = new Chromosome[TravelingSalesman.POPULATION_SIZE];
    for (int i = 0; i < TravelingSalesman.POPULATION_SIZE; i++) {
      chromosomes[i] = new Chromosome(cities);
      chromosomes[i].setCut(cutLength);
      chromosomes[i].setMutation(TravelingSalesman.MUTATION_PERCENT);
    }
    Chromosome.sortChromosomes(chromosomes, TravelingSalesman.POPULATION_SIZE);

    // start up the background thread
    started = true;
    map.update(map.getGraphics());

    generation = 0;

    if (worker != null) worker = null;
    worker = new Thread(this);
    // worker.setPriority(Thread.MIN_PRIORITY);
    worker.start();
  }
Esempio n. 2
1
 /**
  * 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();
 }
  /**
   * 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();
  }
  public SetIfModifiedSince() throws Exception {

    serverSock = new ServerSocket(0);
    int port = serverSock.getLocalPort();

    Thread thr = new Thread(this);
    thr.start();

    Date date = new Date(new Date().getTime() - 1440000); // this time yesterday
    URL url;
    HttpURLConnection con;

    // url = new URL(args[0]);
    url = new URL("http://localhost:" + String.valueOf(port) + "/anything");
    con = (HttpURLConnection) url.openConnection();

    con.setIfModifiedSince(date.getTime());
    con.connect();
    int ret = con.getResponseCode();

    if (ret == 304) {
      System.out.println("Success!");
    } else {
      throw new RuntimeException(
          "Test failed! Http return code using setIfModified method is:"
              + ret
              + "\nNOTE:some web servers are not implemented according to RFC, thus a failed test does not necessarily indicate a bug in setIfModifiedSince method");
    }
  }
  public void onDestroy() {
    running = false;
    if (scanThread != null) scanThread.interrupt();

    if (myWLocate != null) myWLocate.doPause();

    sensorManager.unregisterListener(
        this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));

    if (scanData.getmView() != null) {
      ((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(scanData.getmView());
      scanData.setmView(null);
    }
    try {
      if (wl != null) wl.release();
    } catch (RuntimeException re) {
    }
    wl = null;
    try {
      scanThread.join(1000);
    } catch (InterruptedException ie) {

    }
    System.exit(0);
  }
Esempio n. 6
0
  public static void main(String[] args) {

    Thread thread = new Thread(new Download(args));
    thread.setDaemon(true);
    thread.start();
    try {
      thread.join();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 7
0
  /**
   * Creates an instance.
   *
   * @param pout Source of inputs
   * @param jTextArea Where the inputs are written.
   */
  public JConsoleOutLinker(PipedOutputStream pout, JTextArea jTextArea) {
    try {
      this.pin = new PipedInputStream(pout);
    } catch (IOException ioe) {
      throw new UIError("Unable to create input stream!");
    }
    this.jTextArea = jTextArea;

    thisThread = new Thread(this);
    thisThread.setDaemon(true);
    thisThread.start();
  }
Esempio n. 8
0
  public void run() {

    // setup advertisement message
    advMsg.set_sourceAddr(TOS_UART_ADDR);

    if (reboot) {
      advMsg.set_summary_vNum(0x0);
      advMsg.set_runningVNum(0xffff);
    } else {
      advMsg.set_summary_vNum(0xffff);
      advMsg.set_runningVNum(0x0);
    }
    advMsg.set_summary_numPgsComplete((byte) numPgs);

    while (true) {
      try {
        // send an advertisement message every second
        if (printAllMsgs) System.out.print(advMsg);
        send(advMsg);
        Thread.currentThread().sleep(1000);
        if (reboot) {
          System.exit(0);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
  /**
   * Closes given {@link #transportManagers} of this <tt>Conference</tt> and removes corresponding
   * channel bundle.
   */
  void closeTransportManager(TransportManager transportManager) {
    synchronized (transportManagers) {
      for (Iterator<IceUdpTransportManager> i = transportManagers.values().iterator();
          i.hasNext(); ) {
        if (i.next() == transportManager) {
          i.remove();
          // Presumably, we have a single association for
          // transportManager.
          break;
        }
      }

      // Close manager
      try {
        transportManager.close();
      } catch (Throwable t) {
        logger.warn(
            "Failed to close an IceUdpTransportManager of" + " conference " + getID() + "!", t);
        // The whole point of explicitly closing the
        // transportManagers of this Conference is to prevent memory
        // leaks. Hence, it does not make sense to possibly leave
        // TransportManagers open because a TransportManager has
        // failed to close.
        if (t instanceof InterruptedException) Thread.currentThread().interrupt();
        else if (t instanceof ThreadDeath) throw (ThreadDeath) t;
      }
    }
  }
Esempio n. 10
0
  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];
  } // **********************
Esempio n. 11
0
  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());
  } // **********************
Esempio n. 12
0
  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";
  } // **********************
Esempio n. 13
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);
    }
  }
Esempio n. 14
0
 public void run() {
   while (true) {
     try {
       repaint();
       Thread.sleep(1);
     } catch (Throwable e) {
     }
   }
 }
Esempio n. 15
0
 /**
  * @param log Logger.
  * @param time Time.
  * @param msg Message.
  */
 private static void log0(@Nullable IgniteLogger log, long time, String msg) {
   if (log != null) {
     if (log.isDebugEnabled()) log.debug(msg);
     else log.warning(msg);
   } else
     X.println(
         String.format(
             "[%s][%s]%s",
             DEBUG_DATE_FMT.get().format(time), Thread.currentThread().getName(), msg));
 }
Esempio n. 16
0
 static String waitForInputString() {
   try {
     while (!hasEntered) {
       Thread.sleep(100);
     }
     return inputField.getText();
   } catch (Exception e) {
     return "";
   }
 }
 /**
  * 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) {
     }
   }
 }
Esempio n. 18
0
  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;
  } // ***************************************
Esempio n. 19
0
  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;
    }
  }
  /**
   * Expires this <tt>Conference</tt>, its <tt>Content</tt>s and their respective <tt>Channel</tt>s.
   * Releases the resources acquired by this instance throughout its life time and prepares it to be
   * garbage collected.
   */
  public void expire() {
    synchronized (this) {
      if (expired) return;
      else expired = true;
    }

    EventAdmin eventAdmin = videobridge.getEventAdmin();
    if (eventAdmin != null) eventAdmin.sendEvent(EventFactory.conferenceExpired(this));

    setRecording(false);
    if (recorderEventHandler != null) {
      recorderEventHandler.close();
      recorderEventHandler = null;
    }

    Videobridge videobridge = getVideobridge();

    try {
      videobridge.expireConference(this);
    } finally {
      // Expire the Contents of this Conference.
      for (Content content : getContents()) {
        try {
          content.expire();
        } catch (Throwable t) {
          logger.warn(
              "Failed to expire content " + content.getName() + " of conference " + getID() + "!",
              t);
          if (t instanceof InterruptedException) Thread.currentThread().interrupt();
          else if (t instanceof ThreadDeath) throw (ThreadDeath) t;
        }
      }

      // Close the transportManagers of this Conference. Normally, there
      // will be no TransportManager left to close at this point because
      // all Channels have expired and the last Channel to be removed from
      // a TransportManager closes the TransportManager. However, a
      // Channel may have expired before it has learned of its
      // TransportManager and then the TransportManager will not close.
      closeTransportManagers();

      if (logger.isInfoEnabled()) {
        logger.info(
            "Expired conference " + getID() + ". " + videobridge.getConferenceCountString());
      }
    }
  }
Esempio n. 21
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();
    // /////////////////////////////
  }
 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);
 }
Esempio n. 23
0
  /**
   * Checks if address can be reached using one argument InetAddress.isReachable() version or ping
   * command if failed.
   *
   * @param addr Address to check.
   * @param reachTimeout Timeout for the check.
   * @return {@code True} if address is reachable.
   */
  public static boolean reachableByPing(InetAddress addr, int reachTimeout) {
    try {
      if (addr.isReachable(reachTimeout)) return true;

      String cmd = String.format("ping -%s 1 %s", U.isWindows() ? "n" : "c", addr.getHostAddress());

      Process myProc = Runtime.getRuntime().exec(cmd);

      myProc.waitFor();

      return myProc.exitValue() == 0;
    } catch (IOException ignore) {
      return false;
    } catch (InterruptedException ignored) {
      Thread.currentThread().interrupt();

      return false;
    }
  }
Esempio n. 24
0
  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];
  } // **********************
Esempio n. 25
0
 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) {
   }
 }
Esempio n. 26
0
 public void stop() {
   if (t != null) {
     t.stop();
     t = null;
   }
 }
Esempio n. 27
0
 public void start() {
   if (t == null) {
     t = new Thread(this);
     t.start();
   }
 }
Esempio n. 28
0
    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***************************************************************************************************
Esempio n. 29
0
  // TODO : if start or end is already in the highway, will occur the problem, need to fix
  public static double routingHierarchy(
      long startNode, long endNode, int startTime, int dayIndex, ArrayList<Long> pathNodeList) {
    // System.out.println("start finding the path...");
    int debug = 0;
    try {
      if (!OSMData.nodeHashMap.containsKey(startNode)
          || !OSMData.nodeHashMap.containsKey(endNode)) {
        System.err.println("cannot find start or end node!");
        return -1;
      }

      if (startNode == endNode) {
        System.out.println("start node is the same as end node.");
        return 0;
      }

      NodeInfo start = OSMData.nodeHashMap.get(startNode);
      NodeInfo end = OSMData.nodeHashMap.get(endNode);
      double minDistance = Geometry.calculateDistance(start.getLocation(), end.getLocation());
      if (minDistance < 5) { // use normal A* algorithm to calculate small distance
        return routingAStar(
            start.getNodeId(),
            end.getNodeId(),
            OSMRouteParam.START_TIME,
            OSMRouteParam.DAY_INDEX,
            pathNodeList);
      }

      SearchingSharing sharingData = new SearchingSharing();
      HashMap<Long, NodeInfoHelper> nodeForwardCache = new HashMap<Long, NodeInfoHelper>();
      HashMap<Long, NodeInfoHelper> nodeReverseCache = new HashMap<Long, NodeInfoHelper>();
      ForwardSearching forwardSearching =
          new ForwardSearching(
              startNode, endNode, startTime, dayIndex, sharingData, nodeForwardCache);
      ReverseSearching reverseSearching =
          new ReverseSearching(endNode, startNode, sharingData, nodeReverseCache);
      // two thread run simultaneously
      Thread forwardThread = new Thread(forwardSearching);
      Thread reverseThread = new Thread(reverseSearching);
      // search forward
      forwardThread.start();
      // let forward searching for a while
      // Thread.sleep(100);
      // search reverse
      reverseThread.start();
      // waiting for thread finish
      forwardThread.join();
      reverseThread.join();
      // get the searching intersects
      ArrayList<Long> intersectList = sharingData.getIntersectList();
      // pick the least cost one according to time-dependent
      double minCost = Double.MAX_VALUE;
      ArrayList<Long> minCostPath = new ArrayList<Long>();
      for (long intersect : intersectList) {
        NodeInfoHelper current = nodeForwardCache.get(intersect);
        // cost from source to intersect
        double cost = current.getCost();
        current = nodeReverseCache.get(intersect);
        // update the reverse cost as forward cost
        current.setCost(cost);
        ArrayList<Long> reversePath = new ArrayList<Long>();
        double totalCost = Double.MAX_VALUE;
        // recalculate from intersect to destination
        while (true) {
          long nodeId = current.getNodeId();
          int timeIndex =
              startTime
                  + (int)
                      (current.getCost()
                          / OSMParam.SECOND_PER_MINUTE
                          / OSMRouteParam.TIME_INTERVAL);
          if (timeIndex
              > OSMRouteParam.TIME_RANGE
                  - 1) // time [6am - 9 pm], we regard times after 9pm as constant edge weights
          timeIndex = OSMRouteParam.TIME_RANGE - 1;
          long nextNodeId = current.getParentId();
          double arriveTime = current.getCost();
          // arrive end
          if (nextNodeId == 0) {
            totalCost = arriveTime;
            break;
          }
          // add node
          reversePath.add(nextNodeId);
          // calculate cost according adjlist
          LinkedList<ToNodeInfo> adjNodeList = OSMData.adjListHashMap.get(nodeId);
          double costTime = 0;
          for (ToNodeInfo toNode : adjNodeList) {
            if (toNode.getNodeId() == nextNodeId) {
              int travelTime;
              // forward searching is time dependent
              if (toNode.isFix()) // fix time
              travelTime = toNode.getTravelTime();
              else // fetch from time array
              travelTime = toNode.getSpecificTravelTime(dayIndex, timeIndex);
              costTime = arriveTime + (double) travelTime / OSMParam.MILLI_PER_SECOND;
              break;
            }
          }
          current = nodeReverseCache.get(nextNodeId);
          if (costTime == 0) System.err.println("cost time cannot be zero!");
          else current.setCost(costTime);
        }

        // process the left nodes to real destination
        long lastNode = reversePath.get(reversePath.size() - 1);
        if (lastNode != endNode) {
          NodeInfo last = OSMData.nodeHashMap.get(lastNode);
          NodeInfo dest = OSMData.nodeHashMap.get(endNode);
          EdgeInfo onEdge = last.getEdgeFromNodes(dest);
          current = nodeReverseCache.get(lastNode);
          int totalDistance = onEdge.getDistance();
          int distance;
          long toNodeId;
          if (onEdge.getStartNode() == lastNode) { // from start to middle
            distance = onEdge.getStartDistance(endNode);
            toNodeId = onEdge.getEndNode();
          } else { // from end to middle
            distance = onEdge.getEndDistance(endNode);
            toNodeId = onEdge.getStartNode();
          }
          LinkedList<ToNodeInfo> adjNodeList = OSMData.adjListHashMap.get(lastNode);
          double costTime = 0;
          int timeIndex =
              startTime
                  + (int) (totalCost / OSMParam.SECOND_PER_MINUTE / OSMRouteParam.TIME_INTERVAL);
          if (timeIndex
              > OSMRouteParam.TIME_RANGE
                  - 1) // time [6am - 9 pm], we regard times after 9pm as constant edge weights
          timeIndex = OSMRouteParam.TIME_RANGE - 1;
          for (ToNodeInfo toNode : adjNodeList) {
            if (toNode.getNodeId() == toNodeId) {
              int travelTime;
              // forward searching is time dependent
              if (toNode.isFix()) // fix time
              travelTime = toNode.getTravelTime();
              else // fetch from time array
              travelTime = toNode.getSpecificTravelTime(dayIndex, timeIndex);
              costTime = (double) travelTime / OSMParam.MILLI_PER_SECOND;
              break;
            }
          }
          if (costTime != 0) {
            costTime *= (double) distance / totalDistance;
          }
          totalCost += costTime; // add cost
          reversePath.add(endNode); // add dest
        }

        // if found less cost path, build forward path
        if (totalCost < minCost) {
          ArrayList<Long> forwardPath = new ArrayList<Long>();
          minCost = totalCost;
          current = nodeForwardCache.get(intersect);
          long traceNodeId = current.getParentId();
          while (traceNodeId != 0) {
            forwardPath.add(traceNodeId); // add node
            current = nodeForwardCache.get(traceNodeId);
            traceNodeId = current.getParentId();
          }
          Collections.reverse(forwardPath); // reverse the path list
          // record min-cost path, combine forward path and reverse path
          minCostPath = new ArrayList<Long>();
          minCostPath.addAll(forwardPath);
          minCostPath.add(intersect);
          minCostPath.addAll(reversePath);
          // output kml
          // OSMOutput.generatePathKML(nodeHashMap, pathNodeList, "path_" + intersect);
          // ArrayList<Long> intersectNode = new ArrayList<Long>();
          // intersectNode.add(intersect);
          // OSMOutput.generatePathNodeKML(nodeHashMap, intersectNode, "intersect_" + intersect);
        }
      }
      pathNodeList.addAll(minCostPath);
      return minCost;
    } catch (Exception e) {
      e.printStackTrace();
      System.err.println("routingHierarchy: debug code " + debug);
    }
    return 0;
  }
Esempio n. 30
0
 // Overriding "start()"
 public void start() {
   running = true;
   super.start();
 }