/// The watcher thread - from the Runnable interface.
  // This has to be pretty anal to avoid monitor lockup, lost
  // threads, etc.
  public synchronized void run() {
    Thread me = Thread.currentThread();
    me.setPriority(Thread.MAX_PRIORITY);

    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    startTimeInNs = threadMXBean.getCurrentThreadCpuTime();

    if (enabled.get()) {
      do {
        loop.set(false);
        try {
          wait(millis);
        } catch (InterruptedException e) {
        }
      } while (enabled.get() && loop.get());
    }

    if (enabled.get() && targetThread.isAlive()) {
      isDoneRunning.set(true);

      printThread();
      if (kill) {
        logger.warn(
            "Trying to kill thread with id:"
                + targetThread.getId()
                + " but did not as it can cause deadlocks etc.");
        // targetThread.interrupt();
        // targetThread.stop(); //Never kill thread - it can cause other problems
      }
      done();
      isDoneRunning.set(false);
    }
  }
Example #2
0
 /** Called by ImageJ when the user selects Quit. */
 public void quit() {
   quitMacro = IJ.macroRunning();
   Thread thread = new Thread(this, "Quit");
   thread.setPriority(Thread.NORM_PRIORITY);
   thread.start();
   IJ.wait(10);
 }
  /** Second part of debugger start procedure. */
  private void startDebugger() {
    threadManager = new ThreadManager(this);

    setBreakpoints();
    updateWatches();
    println(bundle.getString("CTL_Debugger_running"), STL_OUT);
    setDebuggerState(DEBUGGER_RUNNING);

    virtualMachine.resume();

    // start refresh thread .................................................
    if (debuggerThread != null) debuggerThread.stop();
    debuggerThread =
        new Thread(
            new Runnable() {
              public void run() {
                for (; ; ) {
                  try {
                    Thread.sleep(5000);
                  } catch (InterruptedException ex) {
                  }
                  if (getState() == DEBUGGER_RUNNING) threadGroup.refresh();
                }
              }
            },
            "Debugger refresh thread"); // NOI18N
    debuggerThread.setPriority(Thread.MIN_PRIORITY);
    debuggerThread.start();
  }
Example #4
0
 public void drop(DropTargetDropEvent dtde) {
   dtde.acceptDrop(DnDConstants.ACTION_COPY);
   DataFlavor[] flavors = null;
   try {
     Transferable t = dtde.getTransferable();
     iterator = null;
     flavors = t.getTransferDataFlavors();
     if (IJ.debugMode) IJ.log("DragAndDrop.drop: " + flavors.length + " flavors");
     for (int i = 0; i < flavors.length; i++) {
       if (IJ.debugMode) IJ.log("  flavor[" + i + "]: " + flavors[i].getMimeType());
       if (flavors[i].isFlavorJavaFileListType()) {
         Object data = t.getTransferData(DataFlavor.javaFileListFlavor);
         iterator = ((List) data).iterator();
         break;
       } else if (flavors[i].isFlavorTextType()) {
         Object ob = t.getTransferData(flavors[i]);
         if (!(ob instanceof String)) continue;
         String s = ob.toString().trim();
         if (IJ.isLinux() && s.length() > 1 && (int) s.charAt(1) == 0) s = fixLinuxString(s);
         ArrayList list = new ArrayList();
         if (s.indexOf("href=\"") != -1 || s.indexOf("src=\"") != -1) {
           s = parseHTML(s);
           if (IJ.debugMode) IJ.log("  url: " + s);
           list.add(s);
           this.iterator = list.iterator();
           break;
         }
         BufferedReader br = new BufferedReader(new StringReader(s));
         String tmp;
         while (null != (tmp = br.readLine())) {
           tmp = java.net.URLDecoder.decode(tmp.replaceAll("\\+", "%2b"), "UTF-8");
           if (tmp.startsWith("file://")) tmp = tmp.substring(7);
           if (IJ.debugMode) IJ.log("  content: " + tmp);
           if (tmp.startsWith("http://")) list.add(s);
           else list.add(new File(tmp));
         }
         this.iterator = list.iterator();
         break;
       }
     }
     if (iterator != null) {
       Thread thread = new Thread(this, "DrawAndDrop");
       thread.setPriority(Math.max(thread.getPriority() - 1, Thread.MIN_PRIORITY));
       thread.start();
     }
   } catch (Exception e) {
     dtde.dropComplete(false);
     return;
   }
   dtde.dropComplete(true);
   if (flavors == null || flavors.length == 0) {
     if (IJ.isMacOSX())
       IJ.error(
           "First drag and drop ignored. Please try again. You can avoid this\n"
               + "problem by dragging to the toolbar instead of the status bar.");
     else IJ.error("Drag and drop failed");
   }
 }
Example #5
0
 /**
  * Create a Thread that will retrieve and display any output. Needs to be high priority, else
  * debugger may exit before it can be displayed.
  */
 private void displayRemoteOutput(final InputStream stream) {
   Thread thr =
       new Thread("output reader") {
         @Override
         public void run() {
           try {
             dumpStream(stream);
           } catch (IOException ex) {
             MessageOutput.fatalError("Failed reading output");
           } finally {
             notifyOutputComplete();
           }
         }
       };
   thr.setPriority(Thread.MAX_PRIORITY - 1);
   thr.start();
 }
Example #6
0
  /** Starts the unicast and multicast receiver threads */
  void startThreads() throws Exception {
    if (ucast_receiver == null) {
      // start the listener thread of the ucast_recv_sock
      ucast_receiver = new UcastReceiver();
      ucast_receiver.start();
      if (Trace.trace) {
        Trace.info("UDP.startThreads()", "created unicast receiver thread");
      }
    }

    if (ip_mcast) {
      if (mcast_receiver != null) {
        if (mcast_receiver.isAlive()) {
          if (Trace.trace) {
            Trace.info(
                "UDP.createThreads()",
                "did not create new multicastreceiver thread as existing "
                    + "multicast receiver thread is still running");
          }
        } else {
          mcast_receiver = null; // will be created just below...
        }
      }

      if (mcast_receiver == null) {
        mcast_receiver = new Thread(this, "UDP mcast receiver");
        mcast_receiver.setPriority(Thread.MAX_PRIORITY); // needed ????
        mcast_receiver.setDaemon(true);
        mcast_receiver.start();
      }
    }
    if (use_outgoing_packet_handler) {
      outgoing_packet_handler.start();
    }
    if (use_incoming_packet_handler) {
      incoming_packet_handler.start();
    }
  }
  private void startFileDownload(
      final String urlString, final String sslCertificate, final File file, final String title) {
    myDownloadingURLs.add(urlString);
    sendDownloaderCallback();

    final int notificationId = NetworkNotifications.Instance().getBookDownloadingId();
    final Notification progressNotification = createDownloadProgressNotification(title);

    final NotificationManager notificationManager =
        (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    myOngoingNotifications.add(Integer.valueOf(notificationId));
    notificationManager.notify(notificationId, progressNotification);

    final Handler progressHandler =
        new Handler() {
          public void handleMessage(Message message) {
            final int progress = message.what;
            final RemoteViews contentView = (RemoteViews) progressNotification.contentView;

            if (progress < 0) {
              contentView.setTextViewText(R.id.download_notification_progress_text, "");
              contentView.setProgressBar(R.id.download_notification_progress_bar, 100, 0, true);
            } else {
              contentView.setTextViewText(
                  R.id.download_notification_progress_text, "" + progress + "%");
              contentView.setProgressBar(
                  R.id.download_notification_progress_bar, 100, progress, false);
            }
            final NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            notificationManager.notify(notificationId, progressNotification);
          }
        };

    final Handler downloadFinishHandler =
        new Handler() {
          public void handleMessage(Message message) {
            myDownloadingURLs.remove(urlString);
            final NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            notificationManager.cancel(notificationId);
            myOngoingNotifications.remove(Integer.valueOf(notificationId));
            notificationManager.notify(
                notificationId, createDownloadFinishNotification(file, title, message.what != 0));
            sendDownloaderCallback();
            doStop();
          }
        };

    final ZLNetworkRequest request =
        new ZLNetworkRequest(urlString, sslCertificate, null) {
          public void handleStream(InputStream inputStream, int length)
              throws IOException, ZLNetworkException {
            final int updateIntervalMillis = 1000; // FIXME: remove hardcoded time constant

            int downloadedPart = 0;
            long progressTime = System.currentTimeMillis() + updateIntervalMillis;
            if (length <= 0) {
              progressHandler.sendEmptyMessage(-1);
            }
            OutputStream outStream;
            try {
              outStream = new FileOutputStream(file);
            } catch (FileNotFoundException ex) {
              throw new ZLNetworkException(ZLNetworkException.ERROR_CREATE_FILE, file.getPath());
            }
            try {
              final byte[] buffer = new byte[8192];
              while (true) {
                final int size = inputStream.read(buffer);
                if (size <= 0) {
                  break;
                }
                downloadedPart += size;
                if (length > 0) {
                  final long currentTime = System.currentTimeMillis();
                  if (currentTime > progressTime) {
                    progressTime = currentTime + updateIntervalMillis;
                    progressHandler.sendEmptyMessage(downloadedPart * 100 / length);
                  }
                  /*if (downloadedPart * 100 / length > 95) {
                  	throw new IOException("debug exception");
                  }*/
                }
                outStream.write(buffer, 0, size);
                /*try {
                	Thread.currentThread().sleep(200);
                } catch (InterruptedException ex) {
                }*/
              }
            } finally {
              outStream.close();
            }
          }
        };

    final Thread downloader =
        new Thread(
            new Runnable() {
              public void run() {
                boolean success = false;
                try {
                  ZLNetworkManager.Instance().perform(request);
                  success = true;
                } catch (ZLNetworkException e) {
                  // TODO: show error message to User
                  e.printStackTrace();
                  file.delete();
                } finally {
                  downloadFinishHandler.sendEmptyMessage(success ? 1 : 0);
                }
              }
            });
    downloader.setPriority(Thread.MIN_PRIORITY);
    downloader.start();
  }
Example #8
0
 /** Called by ImageJ when the user selects Quit. */
 public void quit() {
   Thread thread = new Thread(this, "Quit");
   thread.setPriority(Thread.NORM_PRIORITY);
   thread.start();
   IJ.wait(10);
 }
  public void run() {
    active = true;
    String s = findcachedir();
    uid = getuid(s);
    try {
      File file = new File(s + "main_file_cache.dat");
      if (file.exists() && file.length() > 0x3200000L) file.delete();
      cache_dat = new RandomAccessFile(s + "main_file_cache.dat", "rw");
      for (int j = 0; j < 5; j++)
        cache_idx[j] = new RandomAccessFile(s + "main_file_cache.idx" + j, "rw");

    } catch (Exception exception) {
      exception.printStackTrace();
    }
    for (int i = threadliveid; threadliveid == i; ) {
      if (socketreq != 0) {
        try {
          socket = new Socket(socketip, socketreq);
        } catch (Exception _ex) {
          socket = null;
        }
        socketreq = 0;
      } else if (threadreq != null) {
        Thread thread = new Thread(threadreq);
        thread.setDaemon(true);
        thread.start();
        thread.setPriority(threadreqpri);
        threadreq = null;
      } else if (dnsreq != null) {
        try {
          dns = InetAddress.getByName(dnsreq).getHostName();
        } catch (Exception _ex) {
          dns = "unknown";
        }
        dnsreq = null;
      } else if (savereq != null) {
        if (savebuf != null)
          try {
            FileOutputStream fileoutputstream = new FileOutputStream(s + savereq);
            fileoutputstream.write(savebuf, 0, savelen);
            fileoutputstream.close();
          } catch (Exception _ex) {
          }
        if (waveplay) {
          String wave = s + savereq;
          waveplay = false;
        }
        if (midiplay) {
          midi = s + savereq;
          midiplay = false;
        }
        savereq = null;
      } else if (urlreq != null) {
        try {
          System.out.println("urlstream");
          urlstream = new DataInputStream((new URL(mainapp.getCodeBase(), urlreq)).openStream());
        } catch (Exception _ex) {
          urlstream = null;
        }
        urlreq = null;
      }
      try {
        Thread.sleep(50L);
      } catch (Exception _ex) {
      }
    }
  }
  /**
   * Starts the debugger. The method stops the current debugging (if any) and takes information from
   * the provided info (containing the class to start and arguments to pass it and name of class to
   * stop debugging in) and starts new debugging session.
   *
   * @param info debugger info about class to start
   * @exception DebuggerException if an error occures during the start of the debugger
   */
  public void startDebugger(DebuggerInfo info) throws DebuggerException {
    debuggerInfo = info;
    if (remoteDebugger != null) finishDebugger();
    // S ystem.out.println("startDebugger " + info); // NOI18N
    // RemoteDebugging support
    hostName = null;
    password = null;
    boolean local = true;
    if (info instanceof ReconnectDebuggerInfo) {
      ReconnectDebuggerInfo rdi = (ReconnectDebuggerInfo) info;
      hostName = rdi.getHostName();
      password = rdi.getPassword();
      local = false;
    } else if (info instanceof RemoteDebuggerInfo) {
      hostName = ((RemoteDebuggerInfo) info).getHostName();
      password = ((RemoteDebuggerInfo) info).getPassword();
      local = false;
    }
    boolean stopOnMain = info.getStopClassName() != null;
    stopOnMainFlag = stopOnMain;
    // S ystem.out.println ("ToolsDebugger.startDebugger " + info.getStopClassName ()); // NOI18N
    // T hread.dumpStack ();

    synchronizer = new RequestSynchronizer();

    // open output window ...
    super.startDebugger(info);

    // start & init remote debugger ................................................
    //    process = null;
    if (local) {
      // create process & read password for local debugging

      // create starting string & NbProcessDescriptor
      NbProcessDescriptor debugerProcess;
      if (info instanceof ProcessDebuggerInfo)
        debugerProcess = ((ProcessDebuggerInfo) info).getDebuggerProcess();
      else debugerProcess = ProcessDebuggerType.DEFAULT_DEBUGGER_PROCESS;
      HashMap map;
      if (info instanceof ToolsDebugger10Info) {
        map =
            Utils.processDebuggerInfo(
                info,
                "-debug", // NOI18N
                "sun.tools.debug.EmptyApp" // NOI18N
                );
        map.put(ToolsDebugger10Type.JAVA_HOME_SWITCH, ((ToolsDebugger10Info) info).getJavaHome());
      } else {
        if (info instanceof ToolsDebugger11Info) {
          String javaHome11 = ((ToolsDebugger11Info) info).getJavaHome();
          if ((javaHome11 == null) || (javaHome11.trim().length() == 0)) {
            finishDebugger();
            throw new DebuggerException(bundle.getString("EXC_JDK11_home_is_not_set"));
          }
          map =
              Utils.processDebuggerInfo(
                  info,
                  "-debug -nojit", // NOI18N
                  "sun.tools.debug.EmptyApp" // NOI18N
                  );
          map.put(ToolsDebugger11Type.JAVA_HOME_SWITCH, javaHome11);
        } else {
          map =
              Utils.processDebuggerInfo(
                  info,
                  "-Xdebug", // NOI18N
                  "sun.tools.agent.EmptyApp" // NOI18N
                  );
        }
      }
      MapFormat format = new MapFormat(map);
      String s =
          format.format(
              debugerProcess.getProcessName() + " " + debugerProcess.getArguments() // NOI18N
              );
      println(s, ERR_OUT);

      // start process & read password ......................................
      try {
        process = debugerProcess.exec(format);
        BufferedReader bufferedreader =
            new BufferedReader(new InputStreamReader(process.getInputStream()));
        password = bufferedreader.readLine();
        showOutput(process, ERR_OUT, ERR_OUT);
        connectInput(process);
      } catch (java.lang.Exception e) {
        finishDebugger();
        throw new DebuggerException(
            new MessageFormat(bundle.getString("EXC_While_create_debuggee"))
                .format(
                    new Object[] {format.format(debugerProcess.getProcessName()), e.toString()}),
            e);
      }
      if (password == null) {
        // no reply
        finishDebugger();
        throw new DebuggerException(
            new MessageFormat(bundle.getString("EXC_While_connect_to_debuggee"))
                .format(new Object[] {format.format(debugerProcess.getProcessName())}));
      }
      if (password.indexOf("=") < 0) { // NOI18N
        // unexpected reply
        println(bundle.getString("CTL_Unexpected_reply") + ": " + password, ERR_OUT);
        showOutput(process, ERR_OUT + STD_OUT, ERR_OUT);
        finishDebugger();
        throw new DebuggerException(
            new MessageFormat(bundle.getString("EXC_Unecpected_debugger_reply"))
                .format(new Object[] {password}));
      }
      password = password.substring(password.indexOf("=") + 1); // NOI18N
      println(bundle.getString("CTL_Password") + ": " + password, ERR_OUT);
      hostName = "127.0.0.1"; // NOI18N
    } // end of local debugging specific
    else if (info instanceof ReconnectDebuggerInfo) {
      println(bundle.getString("CTL_Reconnecting"), ERR_OUT | STD_OUT);
    } else
      println(bundle.getString("CTL_Connecting_to") + ": " + hostName + ":" + password, ERR_OUT);

    // start RemoteDebugger ...................................................
    try {
      remoteDebugger =
          new RemoteDebugger(
              hostName,
              password.length() < 1 ? null : password,
              new ToolsCallback(this),
              isShowMessages());
    } catch (java.net.ConnectException e) {
      finishDebugger();
      throw new DebuggerException(
          new MessageFormat(bundle.getString("EXC_Cannot_connect_to_debuggee"))
              .format(new Object[] {e.toString()}),
          e);
    } catch (Throwable e) {
      if (e instanceof ThreadDeath) throw (ThreadDeath) e;
      // e.printStackTrace ();
      finishDebugger();
      throw new DebuggerException(
          new MessageFormat(bundle.getString("EXC_Cannot_connect_to_debuggee"))
              .format(new Object[] {e.toString()}),
          e);
    }

    // create arguments for main class ...............................................
    mainClassName = info.getClassName();
    RemoteClass cls;
    String[] args = null;
    if ((mainClassName != null) && (mainClassName.length() > 0)) {
      String[] infoArgs = info.getArguments();
      args = new String[infoArgs.length + 1];
      args[0] = mainClassName;
      System.arraycopy(infoArgs, 0, args, 1, infoArgs.length);
      // args[0] = name of class
      // args[...] = parameters

      // find main class .........................................................
      try {
        cls = remoteDebugger.findClass(mainClassName);
      } catch (Throwable e) {
        if (e instanceof ThreadDeath) throw (ThreadDeath) e;
        finishDebugger();
        throw new DebuggerException(
            new MessageFormat(bundle.getString("EXC_Cannot_find_class"))
                .format(new Object[] {mainClassName, e.toString()}),
            e);
      }
      if (cls == null) {
        finishDebugger();
        throw new DebuggerException(
            new MessageFormat(bundle.getString("EXC_Cannot_find_class"))
                .format(new Object[] {mainClassName, new ClassNotFoundException().toString()}));
      }
    }

    // set breakpoint on stop class method ...............................................
    if (stopOnMain) {
      RemoteClass stopClass = null;
      try {
        stopClass = remoteDebugger.findClass(stopClassName = info.getStopClassName());
      } catch (Throwable e) {
        if (e instanceof ThreadDeath) throw (ThreadDeath) e;
        println(
            bundle.getString("MSG_Exc_while_finding_class") + stopClassName + '\n' + e, ERR_OUT);
      }
      if (stopClass == null) {
        println(bundle.getString("CTL_No_such_class") + ": " + stopClassName, ERR_OUT);
      } else {
        try {
          RemoteField[] rf = stopClass.getMethods();
          int i, k = rf.length;
          Type t = Type.tMethod(Type.tVoid, new Type[] {Type.tArray(Type.tString)});
          Type startT = Type.tMethod(Type.tVoid);
          RemoteField startM = null;
          RemoteField initM = null;
          RemoteField constM = null;
          for (i = 0; i < k; i++) {
            if (rf[i].getName().equals("main")
                && // NOI18N
                rf[i].getType().equals(t)) break;
            else if (rf[i].getName().equals("start")
                && // NOI18N
                rf[i].getType().equals(startT)) startM = rf[i];
            else if (rf[i].getName().equals("init")
                && // NOI18N
                rf[i].getType().equals(startT)) initM = rf[i];
            else if (rf[i].getName().equals("<init>")
                && // NOI18N
                rf[i].getType().equals(startT)) constM = rf[i];
          }
          if (i < k) // [PENDING] stop on non main too !!!!!!!!!!!!!!!!!!!!!
          stopClass.setBreakpointMethod(rf[i]); // have main
          else if (initM != null) stopClass.setBreakpointMethod(initM);
          else if (startM != null) stopClass.setBreakpointMethod(startM);
          else if (constM != null) stopClass.setBreakpointMethod(constM);

          // S ystem.out.println ("Stop: " + (i <k) + " " + initM +" " + startM +" " + constM); //
          // NOI18N
          /*          pendingBreakpoints = new RemoteField [1];
          pendingBreakpoints [0] = rf[i];
          pendingBreakpointsClass = stopClass;*/
        } catch (Throwable e) {
          if (e instanceof ThreadDeath) throw (ThreadDeath) e;
          println(bundle.getString("MSG_Exc_while_setting_breakpoint") + '\n' + e, ERR_OUT);
        }
      }
    } // stopOnMain

    setBreakpoints();
    updateWatches();
    println(bundle.getString("CTL_Debugger_running"), STL_OUT);
    setDebuggerState(DEBUGGER_RUNNING);

    // run debugged class ...............................................
    if (args != null) {
      RemoteThreadGroup rtg = null;
      try {
        rtg = remoteDebugger.run(args.length, args);
        //        threadGroup.setRemoteThreadGroup (rtg);
      } catch (Throwable e) {
        if (e instanceof ThreadDeath) throw (ThreadDeath) e;
        finishDebugger();
        throw new DebuggerException(
            new MessageFormat(bundle.getString("EXC_While_calling_run"))
                .format(new Object[] {mainClassName, e.toString()}),
            e);
      }
      if (rtg == null) {
        finishDebugger();
        throw new DebuggerException(
            new MessageFormat(bundle.getString("EXC_While_calling_run"))
                .format(
                    new Object[] {
                      mainClassName, "" // NOI18N
                    }));
      }
    }

    // start refresh thread .................................................
    if (debuggerThread != null) debuggerThread.stop();
    debuggerThread =
        new Thread(
            new Runnable() {
              public void run() {
                for (; ; ) {
                  try {
                    Thread.sleep(5000);
                  } catch (InterruptedException ex) {
                  }
                  if (getState() == DEBUGGER_RUNNING)
                    try {
                      threadGroup.threadChanged();

                    } catch (Throwable e) {
                      if (e instanceof ThreadDeath) throw (ThreadDeath) e;
                      if (e instanceof java.net.SocketException) {
                        debuggerThread = null;
                        try {
                          finishDebugger();
                        } catch (Throwable ee) {
                          if (ee instanceof ThreadDeath) throw (ThreadDeath) ee;
                        }
                        Thread.currentThread().stop();
                      }
                    }
                }
              }
            },
            "Debugger refresh thread"); // NOI18N
    debuggerThread.setPriority(Thread.MIN_PRIORITY);
    debuggerThread.start();
  }
 /**
  * Invoked when one of the menus is selected.
  *
  * @param e contains the selected menu item.
  */
 public void actionPerformed(ActionEvent e) {
   Thread thread = new Thread(this);
   thread.setPriority(Resource.getThreadPriority());
   thread.start();
 }