예제 #1
0
    @Override
    public void actionPerformed(ActionEvent e) {
      Frame frame = getFrame();
      JFileChooser chooser = new JFileChooser();
      int ret = chooser.showOpenDialog(frame);

      if (ret != JFileChooser.APPROVE_OPTION) {
        return;
      }

      File f = chooser.getSelectedFile();
      if (f.isFile() && f.canRead()) {
        Document oldDoc = getEditor().getDocument();
        if (oldDoc != null) {
          oldDoc.removeUndoableEditListener(undoHandler);
        }
        if (elementTreePanel != null) {
          elementTreePanel.setEditor(null);
        }
        getEditor().setDocument(new PlainDocument());
        frame.setTitle(f.getName());
        Thread loader = new FileLoader(f, editor.getDocument());
        loader.start();
      } else {
        JOptionPane.showMessageDialog(
            getFrame(),
            "Could not open file: " + f,
            "Error opening file",
            JOptionPane.ERROR_MESSAGE);
      }
    }
예제 #2
0
  private void obtaindate() {
    Thread th =
        new Thread() {

          @Override
          public void run() {

            for (; true; ) {
              Calendar cd = new GregorianCalendar();

              int mon = cd.get(Calendar.MONTH);
              mon++;
              int year = cd.get(Calendar.YEAR);
              int day = cd.get(Calendar.DAY_OF_MONTH);
              date_text.setText("" + day + "/" + mon + "/" + year);

              int hh = cd.get(Calendar.HOUR_OF_DAY);
              int min = cd.get(Calendar.MINUTE);
              int sec = cd.get(Calendar.SECOND);
              time_txt.setText("" + hh + ":" + min + ":" + sec);
              try {
                Thread.sleep(1000);
              } catch (InterruptedException ex) {
                Logger.getLogger(Amin.class.getName()).log(Level.SEVERE, null, ex);
              }
            }
          }
        };
    th.setDaemon(true);
    th.start();
  }
예제 #3
0
 /**
  * Get the current thread's context class loader which is set to the CommonClassLoader by
  * ApplicationServer
  *
  * @return the thread's context classloader if it exists; else the system class loader.
  */
 public static ClassLoader getClassLoader() {
   if (Thread.currentThread().getContextClassLoader() != null) {
     return Thread.currentThread().getContextClassLoader();
   } else {
     return ClassLoader.getSystemClassLoader();
   }
 }
예제 #4
0
  private void RunAllQueriesBtnMouseClicked(
      java.awt.event.MouseEvent evt) { // GEN-FIRST:event_RunAllQueriesBtnMouseClicked
    // TODO add your handling code here:

    qThread = new PBVCPluginQueryThread(this, "", queryList, owlModel);
    Thread qthr = new Thread(qThread);
    qthr.start();
  } // GEN-LAST:event_RunAllQueriesBtnMouseClicked
예제 #5
0
  /** Start the network listening thread. */
  void start() {
    this.running = true;

    Thread thread = new Thread(this, "IceConnector@" + hashCode());

    thread.setDaemon(true);
    thread.start();
  }
예제 #6
0
  public void startConsole(boolean jLine) {
    this.jLine = jLine;

    sender = new ColoredCommandSender();
    Thread thread = new ConsoleCommandThread();
    thread.setName("ConsoleCommandThread");
    thread.setDaemon(true);
    thread.start();
  }
예제 #7
0
  private void RunThisQueryBtnMouseClicked(
      java.awt.event.MouseEvent evt) { // GEN-FIRST:event_RunThisQueryBtnMouseClicked
    // TODO add your handling code here:
    qThread =
        new PBVCPluginQueryThread(
            this, QueriesCmb.getSelectedItem().toString(), SparqlTxtArea.getText(), owlModel);
    Thread qthr = new Thread(qThread);
    qthr.start();

    RunThisQueryBtn.setEnabled(false);
  } // GEN-LAST:event_RunThisQueryBtnMouseClicked
예제 #8
0
  public void startConsole(boolean jLine) {
    this.jLine = jLine;

    sender = new ColoredCommandSender();
    Thread thread = new ConsoleCommandThread();
    thread.setName("ConsoleCommandThread");
    thread.setDaemon(true);
    thread.start();

    /*logger.removeHandler(consoleHandler);
    consoleHandler = new FancyConsoleHandler();
    consoleHandler.setFormatter(new DateOutputFormatter(CONSOLE_DATE));
    logger.addHandler(consoleHandler);*/
  }
예제 #9
0
    public void actionPerformed(ActionEvent e) {
      Frame frame = getFrame();
      JFileChooser chooser = new JFileChooser();
      int ret = chooser.showSaveDialog(frame);

      if (ret != JFileChooser.APPROVE_OPTION) {
        return;
      }

      File f = chooser.getSelectedFile();
      frame.setTitle(f.getName());
      Thread saver = new FileSaver(f, editor.getDocument());
      saver.start();
    }
  private void initDriverList() {
    try {
      Thread thread = Thread.currentThread();
      ClassLoader loader = thread.getContextClassLoader();

      Enumeration iter = loader.getResources("META-INF/services/java.sql.Driver");
      while (iter.hasMoreElements()) {
        URL url = (URL) iter.nextElement();

        ReadStream is = null;
        try {
          is = Vfs.lookup(url.toString()).openRead();

          String filename;

          while ((filename = is.readLine()) != null) {
            int p = filename.indexOf('#');

            if (p >= 0) filename = filename.substring(0, p);

            filename = filename.trim();
            if (filename.length() == 0) continue;

            try {
              Class cl = Class.forName(filename, false, loader);
              Driver driver = null;

              if (Driver.class.isAssignableFrom(cl)) driver = (Driver) cl.newInstance();

              if (driver != null) {
                log.fine(L.l("DatabaseManager adding driver '{0}'", driver.getClass().getName()));

                _driverList.add(driver);
              }
            } catch (Exception e) {
              log.log(Level.FINE, e.toString(), e);
            }
          }
        } catch (Exception e) {
          log.log(Level.FINE, e.toString(), e);
        } finally {
          if (is != null) is.close();
        }
      }
    } catch (Exception e) {
      log.log(Level.FINE, e.toString(), e);
    }
  }
 private void rest() {
   try {
     Thread.sleep(100); // do nothing for 1000 miliseconds (1 second)
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }
예제 #12
0
    /**
     * The run method lives for the life of the JobTracker, and removes Jobs that are not still
     * running, but which finished a long time ago.
     */
    public void run() {
      while (shouldRun) {
        try {
          Thread.sleep(RETIRE_JOB_CHECK_INTERVAL);
        } catch (InterruptedException ie) {
        }

        synchronized (jobs) {
          synchronized (jobInitQueue) {
            synchronized (jobsByArrival) {
              for (Iterator it = jobs.keySet().iterator(); it.hasNext(); ) {
                String jobid = (String) it.next();
                JobInProgress job = (JobInProgress) jobs.get(jobid);

                if (job.getStatus().getRunState() != JobStatus.RUNNING
                    && job.getStatus().getRunState() != JobStatus.PREP
                    && (job.getFinishTime() + RETIRE_JOB_INTERVAL < System.currentTimeMillis())) {
                  it.remove();

                  jobInitQueue.remove(job);
                  jobsByArrival.remove(job);
                }
              }
            }
          }
        }
      }
    }
예제 #13
0
 protected void runEcho() {
   Scanner socketScanner = null;
   String newLine;
   try {
     socketScanner = new Scanner(socket.getInputStream());
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   while (true) {
     try {
       Thread.sleep(CLERK_DELAY_MS);
     } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
     if (socket.isClosed()) return;
     if (socketScanner.hasNextLine()) {
       newLine = socketScanner.nextLine() + END_OF_LINE;
       System.out.println("echoing: " + newLine);
       try {
         socket.getOutputStream().write(newLine.getBytes(encoding));
       } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
       }
     }
   }
 }
예제 #14
0
    public void run() {
      while (!_closed) {
        try {
          updateAll();

          long now = System.currentTimeMillis();
          if (inetAddrCacheMS > 0 && _nextResolveTime < now) {
            _nextResolveTime = now + inetAddrCacheMS;
            for (Node node : _all) {
              node.updateAddr();
            }
          }

          // force check on master
          // otherwise master change may go unnoticed for a while if no write concern
          _mongo.getConnector().checkMaster(true, false);
        } catch (Exception e) {
          _logger.log(Level.WARNING, "couldn't do update pass", e);
        }

        try {
          Thread.sleep(updaterIntervalMS);
        } catch (InterruptedException ie) {
        }
      }
    }
  @Override
  public void render(RenderRequest portletReq, RenderResponse portletResp)
      throws PortletException, IOException {
    LOGGER.entering(LOG_CLASS, "main portlet render entry");

    long tid = Thread.currentThread().getId();
    portletReq.setAttribute(THREADID_ATTR, tid);

    PrintWriter writer = portletResp.getWriter();

    writer.write(
        "<div id=\"DispatcherTests_SPEC2_19_ForwardServletResource\">no resource output.</div>\n");
    ResourceURL resurl = portletResp.createResourceURL();
    resurl.setCacheability(PAGE);
    writer.write("<script>\n");
    writer.write("(function () {\n");
    writer.write("   var xhr = new XMLHttpRequest();\n");
    writer.write("   xhr.onreadystatechange=function() {\n");
    writer.write("      if (xhr.readyState==4 && xhr.status==200) {\n");
    writer.write(
        "         document.getElementById(\"DispatcherTests_SPEC2_19_ForwardServletResource\").innerHTML=xhr.responseText;\n");
    writer.write("      }\n");
    writer.write("   };\n");
    writer.write("   xhr.open(\"GET\",\"" + resurl.toString() + "\",true);\n");
    writer.write("   xhr.send();\n");
    writer.write("})();\n");
    writer.write("</script>\n");
  }
예제 #16
0
  /**
   * Creates a new DAG-based graph layout for the given Bayesian Network. The nodes are identified
   * by a string label, and the edges by a number.
   *
   * @param bn the Bayesian network
   * @return the generated layout
   */
  private Layout<String, Integer> getGraphLayout(DialogueState ds, boolean showParameters) {
    Forest<String, Integer> f = new DelegateForest<String, Integer>();

    // adding the nodes and edges
    int counter = 0;
    try {
      for (BNode node : new ArrayList<BNode>(ds.getNodes())) {
        if (showParameters || !ds.getParameterIds().contains(node.getId())) {
          String nodeName = getVerticeId(node);

          f.addVertex(nodeName);
          for (BNode inputNode : new ArrayList<BNode>(node.getInputNodes())) {
            if (ds.getNode(inputNode.getId()) != null) {
              String inputNodeName = getVerticeId(inputNode);
              f.addEdge(counter, inputNodeName, nodeName);
              counter++;
            }
          }
        }
      }

      CustomLayoutTransformer transformer = new CustomLayoutTransformer(ds);
      StaticLayout<String, Integer> layout = new StaticLayout<String, Integer>(f, transformer);

      layout.setSize(new Dimension(600, 600));

      return layout;
    } catch (ConcurrentModificationException | NullPointerException e) {
      try {
        Thread.sleep(50);
      } catch (InterruptedException e1) {
      }
      return getGraphLayout(ds, showParameters);
    }
  }
예제 #17
0
 /**
  * Generates new simulated observations and adds them to the dialogue state. The method returns
  * true when a new user input has been generated, and false otherwise.
  *
  * @return whether a user input has been generated @
  */
 private boolean addNewObservations() {
   List<String> newObsVars = new ArrayList<String>();
   for (String var : simulatorState.getChanceNodeIds()) {
     if (var.contains("^o'")) {
       newObsVars.add(var);
     }
   }
   if (!newObsVars.isEmpty()) {
     MultivariateDistribution newObs = simulatorState.queryProb(newObsVars);
     for (String newObsVar : newObsVars) {
       newObs.modifyVariableId(newObsVar, newObsVar.replace("^o'", ""));
     }
     while (system.isPaused()) {
       try {
         Thread.sleep(50);
       } catch (InterruptedException e) {
       }
     }
     if (!newObs.getValues().isEmpty()) {
       if (newObs.getVariables().contains(system.getSettings().userInput)) {
         log.fine("Simulator output: " + newObs + "\n --------------");
         system.addContent(newObs);
         return true;
       } else {
         log.fine("Contextual variables: " + newObs);
         system.addContent(newObs);
       }
     }
   }
   return false;
 }
예제 #18
0
    public void run() {
      int i;
      String cmdToLookFor = getServerProperty("pidHint");
      if (cmdToLookFor == null) {
        StringBuffer buf = new StringBuffer();
        for (i = 0; i < mExecArgs.length; i++) {
          if (i > 0) {
            buf.append(" ");
          }
          buf.append(mExecArgs[i]);
        }
        cmdToLookFor = buf.toString();
      }

      mLogger.finer("Looking for pid for command: " + cmdToLookFor);

      i = 0;
      do {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException ie) {
        }
        mPid = UnixStdlib.getProcessID(cmdToLookFor);
      } while (mPid == 0 && ++i < 300); // up to 5 minutes

      if (mPid == 0) {
        mLogger.warning("Giving up on trying to identify pid");
      } else {
        mLogger.finer("Serverpid server=" + mName + " pid=" + mPid);
      }
    }
  /** Looks up the local database, creating if necessary. */
  private DataSource findDatabaseImpl(String url, String driverName) throws SQLException {
    try {
      synchronized (_databaseMap) {
        DBPool db = _databaseMap.get(url);

        if (db == null) {
          db = new DBPool();

          db.setVar(url + "-" + _gId++);

          DriverConfig driver = db.createDriver();

          ClassLoader loader = Thread.currentThread().getContextClassLoader();

          Class driverClass = Class.forName(driverName, false, loader);

          driver.setType(driverClass);
          driver.setURL(url);

          db.init();

          _databaseMap.put(url, db);
        }

        return db;
      }
    } catch (RuntimeException e) {
      throw e;
    } catch (SQLException e) {
      throw e;
    } catch (Exception e) {
      throw ConfigException.create(e);
    }
  }
예제 #20
0
  /**
   * Execute Task locally and wait
   *
   * @param cmd command
   * @return execution info
   */
  public String executeLocal(String cmd) {
    log.config(cmd);
    if (m_task != null && m_task.isAlive()) m_task.interrupt();

    m_task = new Task(cmd);
    m_task.start();

    StringBuffer sb = new StringBuffer();
    while (true) {
      //  Give it a bit of time
      try {
        Thread.sleep(500);
      } catch (InterruptedException ioe) {
        log.log(Level.SEVERE, cmd, ioe);
      }
      //  Info to user
      sb.append(m_task.getOut())
          .append("\n-----------\n")
          .append(m_task.getErr())
          .append("\n-----------");

      //  Are we done?
      if (!m_task.isAlive()) break;
    }
    log.config("done");
    return sb.toString();
  } //	executeLocal
예제 #21
0
  public void run() {
    List<UCFTestPathData> testData = m_testData.getTestPaths();
    int len = testData.size();
    // System.out.println("about to start "+ len + " users");
    String docbase = m_testData.getDocbase();
    int thinkTime = m_testData.getThinktime();

    // generating specified number of user threads
    WorkerThread[] workers = new WorkerThread[len];

    // should new a thread to serve every user
    for (int i = 0; i < len; i++) {
      UCFTestPathData data = testData.get(i);
      List<String> items = DocbaseHelper.buildWorkItems(data, docbase);
      workers[i] = new WorkerThread(docbase, m_url, data, thinkTime, items);
    }

    int rampup = m_testData.getRmpup() * 1000;
    // start workers
    try {
      for (int i = 0; i < len; i++) {
        workers[i].start();

        // add rampup time
        Thread.sleep(rampup);
      }

      // wait for all works done
      for (int i = 0; i < len; i++) workers[i].join();
    } catch (InterruptedException ignored) {
    }
  }
예제 #22
0
  /**
   * Creates and starts the {@link #sendKeepAliveMessageThread} which is to send STUN keep-alive
   * <tt>Message</tt>s to the STUN server associated with the <tt>StunCandidateHarvester</tt> of
   * this instance in order to keep the <tt>Candidate</tt>s harvested by this instance alive.
   */
  private void createSendKeepAliveMessageThread() {
    synchronized (sendKeepAliveMessageSyncRoot) {
      Thread t = new SendKeepAliveMessageThread(this);
      t.setDaemon(true);
      t.setName(getClass().getName() + ".sendKeepAliveMessageThread: " + hostCandidate);

      boolean started = false;

      sendKeepAliveMessageThread = t;
      try {
        t.start();
        started = true;
      } finally {
        if (!started && (sendKeepAliveMessageThread == t)) sendKeepAliveMessageThread = null;
      }
    }
  }
  @Override
  public void serveResource(ResourceRequest portletReq, ResourceResponse portletResp)
      throws PortletException, IOException {
    LOGGER.entering(LOG_CLASS, "main portlet serveResource entry");

    long tid = Thread.currentThread().getId();
    portletReq.setAttribute(THREADID_ATTR, tid);

    PrintWriter writer = portletResp.getWriter();
  }
예제 #24
0
  protected int pick(int iThink, boolean couldCreate) {
    final int id = Thread.currentThread().hashCode();
    final int s = _availSafe.size();
    for (int i = 0; i < s; i++) {
      DBPort p = _availSafe.get(i);
      if (p._lastThread == id) return i;
    }

    if (couldCreate) return -1;
    return iThink;
  }
  @Override
  public void processAction(ActionRequest portletReq, ActionResponse portletResp)
      throws PortletException, IOException {
    LOGGER.entering(LOG_CLASS, "main portlet processAction entry");

    portletResp.setRenderParameters(portletReq.getParameterMap());
    long tid = Thread.currentThread().getId();
    portletReq.setAttribute(THREADID_ATTR, tid);

    StringWriter writer = new StringWriter();
  }
예제 #26
0
  // ----This function getting nodes from mongo's collection tree_nodes----
  // ---------the function insert nodes to neo4j and deletes it from mongo-----------
  // ----------------------------------------------------------------------------------------
  public void update_tree() {
    while (true) {
      DBObject obj = new BasicDBObject();
      obj.put("in_process", 0); // when other thread processing, 'in_process'=1
      DBCursor cursor = this.colltree.find(obj); // find only documents not in use of other thread
      // log4j.info(cursor.count() + " documents to process in collection tree nodes");
      if (!cursor.hasNext()) { // no documents to process
        try {
          log4j.info("there is no nodes to process at the moment, going to sleep for 10 seconds");
          Thread.currentThread();
          Thread.sleep(1000 * 10);
          log4j.info("update_tree woke up, continues");
        } catch (InterruptedException e) {
          log4j.error("InterruptedException caught, at update_all_tweets");
          e.printStackTrace();
          log4j.error(e);
        }
      } else // there are documents to process
      {
        try {
          while (cursor.hasNext()) {
            DBObject tr = cursor.next();
            try {
              String parent = tr.get("parent").toString();
              String[] sons = tr.get("son").toString().split(","); // make array of sons
              neo4j.addNode(
                  parent, sons, this.log4j); // create nodes and relationships if not exists
              this.colltree.remove(tr); // remove document from collection

            } catch (ConcurrentModificationException e) {
              // log4j.error(e);
              log4j.warn(e);
            }
          }
        } catch (MongoException e) {
          log4j.error(e);
        }
      }
    }
  }
예제 #27
0
    @Override
    @SuppressWarnings("SleepWhileHoldingLock")
    public void run() {
      try {
        // initialize the statusbar
        status.removeAll();
        JProgressBar progress = new JProgressBar();
        progress.setMinimum(0);
        progress.setMaximum(doc.getLength());
        status.add(progress);
        status.revalidate();

        // start writing
        Writer out = new FileWriter(f);
        Segment text = new Segment();
        text.setPartialReturn(true);
        int charsLeft = doc.getLength();
        int offset = 0;
        while (charsLeft > 0) {
          doc.getText(offset, Math.min(4096, charsLeft), text);
          out.write(text.array, text.offset, text.count);
          charsLeft -= text.count;
          offset += text.count;
          progress.setValue(offset);
          try {
            Thread.sleep(10);
          } catch (InterruptedException e) {
            Logger.getLogger(FileSaver.class.getName()).log(Level.SEVERE, null, e);
          }
        }
        out.flush();
        out.close();
      } catch (IOException e) {
        final String msg = e.getMessage();
        SwingUtilities.invokeLater(
            new Runnable() {

              public void run() {
                JOptionPane.showMessageDialog(
                    getFrame(),
                    "Could not save file: " + msg,
                    "Error saving file",
                    JOptionPane.ERROR_MESSAGE);
              }
            });
      } catch (BadLocationException e) {
        System.err.println(e.getMessage());
      }
      // we are done... get rid of progressbar
      status.removeAll();
      status.revalidate();
    }
예제 #28
0
 /**
  * This method can be called to wait until the application has been launched. The caller thread
  * will be blocked until the application has been launched. This method will return immediately if
  * the application has already been launched when it is called.
  */
 public static void waitUntilLaunched() {
   AppLogger.finer("called, thread=" + Thread.currentThread());
   synchronized (LAUNCH_LOCK) {
     while (isLaunching) {
       try {
         AppLogger.finer("waiting");
         LAUNCH_LOCK.wait();
       } catch (InterruptedException e) {
         // will loop
       }
     }
   }
 }
  public static void main(String[] args) throws Exception {
    int counter = 0;
    while (true) {
      Thread outThread = null;
      Thread errThread = null;
      try {
        // org.pitest.mutationtest.instrument.MutationTestUnit#runTestInSeperateProcessForMutationRange

        // *** start slave

        ServerSocket commSocket = new ServerSocket(0);
        int commPort = commSocket.getLocalPort();
        System.out.println("commPort = " + commPort);

        // org.pitest.mutationtest.execute.MutationTestProcess#start
        //   - org.pitest.util.CommunicationThread#start
        FutureTask<Integer> commFuture = createFuture(commSocket);
        //   - org.pitest.util.WrappingProcess#start
        //       - org.pitest.util.JavaProcess#launch
        Process slaveProcess = startSlaveProcess(commPort);
        outThread = new Thread(new ReadFromInputStream(slaveProcess.getInputStream()), "stdout");
        errThread = new Thread(new ReadFromInputStream(slaveProcess.getErrorStream()), "stderr");
        outThread.start();
        errThread.start();

        // *** wait for slave to die

        // org.pitest.mutationtest.execute.MutationTestProcess#waitToDie
        //    - org.pitest.util.CommunicationThread#waitToFinish
        System.out.println("waitToFinish");
        Integer controlReturned = commFuture.get();
        System.out.println("controlReturned = " + controlReturned);
        // NOTE: the following won't get called if commFuture.get() fails!
        //    - org.pitest.util.JavaProcess#destroy
        outThread.interrupt(); // org.pitest.util.AbstractMonitor#requestStop
        errThread.interrupt(); // org.pitest.util.AbstractMonitor#requestStop
        slaveProcess.destroy();
      } catch (Exception e) {
        e.printStackTrace(System.out);
      }

      // test: the threads should exit eventually
      outThread.join();
      errThread.join();
      counter++;
      System.out.println("try " + counter + ": stdout and stderr threads exited normally");
    }
  }
예제 #30
0
  /** Utility routine for setting the context class loader. Returns previous class loader. */
  public static ClassLoader setContextClassLoader(ClassLoader newClassLoader) {

    // Can only reference final local variables from dopriveleged block
    final ClassLoader classLoaderToSet = newClassLoader;

    final Thread currentThread = Thread.currentThread();
    ClassLoader originalClassLoader = currentThread.getContextClassLoader();

    if (classLoaderToSet != originalClassLoader) {
      if (System.getSecurityManager() == null) {
        currentThread.setContextClassLoader(classLoaderToSet);
      } else {
        java.security.AccessController.doPrivileged(
            new java.security.PrivilegedAction() {
              public java.lang.Object run() {
                currentThread.setContextClassLoader(classLoaderToSet);
                return null;
              }
            });
      }
    }
    return originalClassLoader;
  }