Пример #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
 public void stopEvaluate() {
   // user requested run be stopped so tell
   // run thread to stop
   Thread tmp = runThread;
   runThread = null;
   tmp.interrupt();
 }
Пример #3
0
  //    public static final String showElementTreeAction = "showElementTree";
  // -------------------------------------------------------------
  public void openFile(String currDirStr, String currFileStr) {

    if (fileDialog == null) {
      fileDialog = new FileDialog(this);
    }
    fileDialog.setMode(FileDialog.LOAD);
    if (!(currDirStr.equals(""))) {
      fileDialog.setDirectory(currDirStr);
    }
    if (!(currFileStr.equals(""))) {
      fileDialog.setFile(currFileStr);
    }
    fileDialog.show();

    String file = fileDialog.getFile(); // cancel pushed
    if (file == null) {
      return;
    }
    String directory = fileDialog.getDirectory();
    File f = new File(directory, file);
    if (f.exists()) {
      Document oldDoc = getEditor().getDocument();
      if (oldDoc != null)
        // oldDoc.removeUndoableEditListener(undoHandler);
        /*
          if (elementTreePanel != null) {
          elementTreePanel.setEditor(null);
          }
        */
        getEditor().setDocument(new PlainDocument());
      fileDialog.setTitle(file);
      Thread loader = new FileLoader(f, editor1.getDocument());
      loader.start();
    }
  }
Пример #4
0
 private void messageStresser() throws HeadlessException {
   String res = JOptionPane.showInputDialog(this, "Number of messages to send");
   try {
     int count = Integer.parseInt(res);
     Thread t = new Thread(new Stresser(count));
     t.start();
   } catch (NumberFormatException nfe) {
   }
 }
Пример #5
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();
    }
Пример #6
0
  private void doRun(final Test testSuite) {
    setButtonLabel(fRun, "Stop");
    fRunner =
        new Thread("TestRunner-Thread") {
          public void run() {
            UnitTestRunner.this.start(testSuite);
            postInfo("Running...");

            long startTime = System.currentTimeMillis();
            testSuite.run(fTestResult);

            if (fTestResult.shouldStop()) {
              postInfo("Stopped");
            } else {
              long endTime = System.currentTimeMillis();
              long runTime = endTime - startTime;
              postInfo("Finished: " + elapsedTimeAsString(runTime) + " seconds");
            }
            runFinished(testSuite);
            setButtonLabel(fRun, "Run");
            showIDE(true);
            fRunner = null;
            System.gc();
          }
        };
    // make sure that the test result is created before we start the
    // test runner thread so that listeners can register for it.
    fTestResult = createTestResult();
    fTestResult.addListener(UnitTestRunner.this);
    aboutToStart(testSuite);

    fRunner.start();
  }
Пример #7
0
  @Override
  public synchronized void run() {
    try {
      for (int i = 0; i < NUM_PIPES; i++) {
        while (Thread.currentThread() == reader[i]) {
          try {
            this.wait(100);
          } catch (InterruptedException ie) {
          }
          if (pin[i].available() != 0) {
            String input = this.readLine(pin[i]);
            appendMsg(htmlize(input));
            if (textArea.getDocument().getLength() > 0) {
              textArea.setCaretPosition(textArea.getDocument().getLength() - 1);
            }
          }
          if (quit) {
            return;
          }
        }
      }

    } catch (Exception e) {
      Debug.error(me + "Console reports an internal error:\n%s", e.getMessage());
    }
  }
Пример #8
0
 public void start() {
   Dimension size = getSize();
   for (int i = 0; i < animpts.length; i += 2) {
     animpts[i + 0] = (float) (Math.random() * size.width);
     animpts[i + 1] = (float) (Math.random() * size.height);
     deltas[i + 0] = (float) (Math.random() * 4.0 + 2.0);
     deltas[i + 1] = (float) (Math.random() * 4.0 + 2.0);
     if (animpts[i + 0] > size.width / 6.0f) {
       deltas[i + 0] = -deltas[i + 0];
     }
     if (animpts[i + 1] > size.height / 6.0f) {
       deltas[i + 1] = -deltas[i + 1];
     }
   }
   anim = new Thread(this);
   anim.setPriority(Thread.MIN_PRIORITY);
   anim.start();
 }
Пример #9
0
 public void run() { // how to let this terminate gracefully?
   while (1 != 2) {
     try {
       Thread.sleep(_period);
       updateDisplay();
     } catch (InterruptedException e) {
     }
   }
 }
Пример #10
0
 public void run() {
   while (runner == Thread.currentThread() && running) { // running){
     sec++;
     if (sec == 60) {
       sec = 0;
       min++;
       if (min == 60) {
         min = 0;
         hour++;
       }
     }
     redraw();
     // define thread task
     try {
       Thread.sleep(1000);
     } catch (InterruptedException e) {
       System.out.println("Thread failed");
     }
   }
 }
Пример #11
0
 private void waitForAllToLock() {
   for (Peer p : dec.getPeers()) {
     while (!p.isLocked() && p.isConnected()) {
       try {
         Thread.sleep(100);
       } catch (InterruptedException e) {
       }
     }
     p.setLocked(false);
   }
 }
Пример #12
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();
    }
Пример #13
0
  /**
   * Added this guy to make sure an image is loaded - ie no broken images. So far its used only for
   * images loaded off the disk (non-URL). It seems to work marvelously. By the way, it does the
   * same thing as MediaTracker, but you dont need to know the component its being rendered on. Rob
   */
  private void waitForImage() throws InterruptedException {
    int w = fImage.getWidth(this);
    int h = fImage.getHeight(this);

    while (true) {
      int flags = Toolkit.getDefaultToolkit().checkImage(fImage, w, h, this);

      if (((flags & ERROR) != 0) || ((flags & ABORT) != 0)) throw new InterruptedException();
      else if ((flags & (ALLBITS | FRAMEBITS)) != 0) return;
      Thread.sleep(10);
      // System.out.println("rise and shine...");
    }
  }
Пример #14
0
 public void run() {
   try {
     while (keepRunning) {
       if (Client.currentInstance.session != null
           && Client.currentInstance.session.isConnected()) {
         Client.currentInstance.session.postMessage("", cmd, "");
       }
       try {
         Thread.currentThread().sleep(interval);
       } catch (InterruptedException ex) {
       }
     }
   } catch (Exception ex2) {
   }
 }
Пример #15
0
  public void testDeadlock49178() throws Exception {
    // open the document
    final StyledDocument docu = support.openDocument();

    // start closing it
    Thread closing =
        new Thread(
            new Runnable() {
              public void run() {
                support.close(false); // will block in notifyUnmodified()
                closingDone = true;
              }
            });
    closing.start();

    Thread processing =
        new Thread(
            new Runnable() {
              boolean second = false;

              public void run() {
                if (!second) {
                  second = true;
                  docu.render(this);
                  //                    NbDocument.runAtomic(docu, this);
                } else { // inside readLock
                  support.createPositionRef(0, Position.Bias.Forward);
                  processingDone = true;
                }
              }
            });

    synchronized (waitLock) {
      while (!inWait) waitLock.wait();
    }

    processing.start();

    Thread.sleep(1000);
    synchronized (waitLock) {
      shouldWait = false;
      waitLock.notifyAll();
    }

    closing.join(10000);
    processing.join(10000);
    assertNull("No exception thrown", exception);
    assertTrue("Closing thread finished", closingDone);
    assertTrue("Processing thread finished", processingDone);
  }
Пример #16
0
    @Override
    public String doInBackground() {
      System.out.println("Strart Job Monitoring Worker");
      String out = "";
      String defStatus = "Unknown";
      starttime = System.nanoTime();

      CURRENT_STATUS = RUN_STATUS.NOT_RUN;

      try {

        while (CURRENT_STATUS == RUN_STATUS.ACTIVE
            || CURRENT_STATUS == RUN_STATUS.SUBMITTED
            || CURRENT_STATUS == RUN_STATUS.NOT_RUN) {

          List<String> resultsToPublish = new ArrayList<String>();
          int updateTimeInMS = (int) (updateTimeInSeconds * 1000);
          Thread.sleep(updateTimeInMS);

          // get job status
          String status =
              Run.getJobStatusOnServer(jobid, defStatus, account, url, user, expName, password);
          resultsToPublish.add(0, defStatus);
          CURRENT_STATUS = RUN_STATUS.getStatus(status);

          // get outputs
          Run.getStatusFileFromServer(
              jobid, account, url, user, expName, analysDir, password, statusUpdateFiles);

          String report = "";
          if (statusUpdateFiles.exists()) {
            report = IO.readFileToString(statusUpdateFiles);
          }

          publish(report);
        }

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

      } finally {

        publish(out);
      }
      return out;
    }
Пример #17
0
 /**
  * The disconnect method will stop the eventreplayer, and send null to the other peers, to stop
  * their reading from their streams. The GUI-menu is updated appropriately.
  */
 public void disconnect() {
   setTitle("Disconnected");
   active = false;
   if (connected == true) {
     er.stopStreamToQueue();
     ert.interrupt();
     setDocumentFilter(null);
     connected = false;
     setLocked(false);
   }
   deregisterOnPort();
   Disconnect.setEnabled(false);
   Connect.setEnabled(true);
   Listen.setEnabled(true);
   Save.setEnabled(true);
   SaveAs.setEnabled(true);
 }
Пример #18
0
 public void run() {
   while (true) {
     synchronized (semaphore) {
       try {
         semaphore.wait();
       } catch (InterruptedException ex) {
       }
     }
     Color origColor = c.getBackground();
     for (int i = 0; i < flashCount; i++) {
       c.setBackground(flashColor);
       try {
         Thread.currentThread().sleep(100);
       } catch (Exception ex) {
       }
       c.setBackground(origColor);
     }
   }
 }
Пример #19
0
 public static void sleep(int ms) {
   try {
     Thread.sleep(ms);
   } catch (Exception e) {
   }
 }
Пример #20
0
    public void start() {
      running = true;
      if (runner == null) runner = new Thread(this);

      runner.start();
    }
Пример #21
0
        public void actionPerformed(ActionEvent e) {
          saveOld();
          area1.setText("");
          resetArea2();
          try {
            clientSocket = new Socket(ipaddress.getText(), Integer.parseInt(portNumber.getText()));
            Random r = new Random();
            serverport = 10000 + r.nextInt(8999); // random port :D

            serverSocket = new ServerSocket(serverport);
            active = true;
            editor.setTitleToListen();

            connected = true;

            ObjectOutputStream output = new ObjectOutputStream(clientSocket.getOutputStream());
            ObjectInputStream input = new ObjectInputStream(clientSocket.getInputStream());
            output.writeObject(new JoinNetworkRequest(serverport));

            ConnectionData data = getConnectionData(clientSocket, input);

            lc = new LamportClock(data.getId());
            lc.setMaxTime(data.getTs());
            dec = new DocumentEventCapturer(lc, editor);
            er = new EventReplayer(editor, dec, lc);
            ert = new Thread(er);
            ert.start();

            Peer peer =
                new Peer(
                    editor,
                    er,
                    data.getHostId(),
                    clientSocket,
                    output,
                    input,
                    lc,
                    clientSocket.getInetAddress().getHostAddress(),
                    data.getPort());
            dec.addPeer(peer);
            Thread thread = new Thread(peer);
            thread.start();

            er.setAcknowledgements(data.getAcknowledgements());
            er.setEventHistory(data.getEventHistory());
            er.setCarets(data.getCarets());

            er.addCaretPos(lc.getID(), 0);

            for (PeerWrapper p : data.getPeers()) {
              Socket socket;
              try {
                socket = connectToPeer(p.getIP(), p.getPort());
                ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
                ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
                outputStream.writeObject(
                    new NewPeerDataRequest(lc.getID(), serverSocket.getLocalPort(), 0));
                Peer newPeer =
                    new Peer(
                        editor,
                        er,
                        p.getId(),
                        socket,
                        outputStream,
                        inputStream,
                        lc,
                        p.getIP(),
                        p.getPort());
                dec.addPeer(newPeer);
                Thread t = new Thread(newPeer);
                t.start();
              } catch (IOException ex) {
                continue;
              }
            }

            Thread t1 =
                new Thread(
                    new Runnable() {

                      @Override
                      public void run() {
                        waitForConnection();
                      }
                    });
            t1.start();
            area1.setText(data.getTextField());
            area1.setCaretPosition(0);
            setDocumentFilter(dec);

            dec.sendObjectToAllPeers(new UnlockRequest(lc.getTimeStamp()));

            changed = false;
            Connect.setEnabled(false);
            Disconnect.setEnabled(true);
            Listen.setEnabled(false);
            Save.setEnabled(false);
            SaveAs.setEnabled(false);
          } catch (NumberFormatException | IOException e1) {
            setTitle("Unable to connect");
          }
        }
Пример #22
0
  public void run() {
    Thread me = Thread.currentThread();
    while (getSize().width <= 0) {
      try {
        anim.sleep(500);
      } catch (InterruptedException e) {
        return;
      }
    }

    Graphics2D g2d = null;
    Graphics2D BufferG2D = null;
    Graphics2D ScreenG2D = null;
    BasicStroke solid = new BasicStroke(9.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 9.0f);
    GeneralPath gp = new GeneralPath(GeneralPath.WIND_NON_ZERO);
    int rule = AlphaComposite.SRC_OVER;
    AlphaComposite opaque = AlphaComposite.SrcOver;
    AlphaComposite blend = AlphaComposite.getInstance(rule, 0.9f);
    AlphaComposite set = AlphaComposite.Src;
    int frame = 0;
    int frametmp = 0;
    Dimension oldSize = getSize();
    Shape clippath = null;
    while (anim == me) {
      Dimension size = getSize();
      if (size.width != oldSize.width || size.height != oldSize.height) {
        img = null;
        clippath = null;
        if (BufferG2D != null) {
          BufferG2D.dispose();
          BufferG2D = null;
        }
        if (ScreenG2D != null) {
          ScreenG2D.dispose();
          ScreenG2D = null;
        }
      }
      oldSize = size;

      if (img == null) {
        img = (BufferedImage) createImage(size.width, size.height);
      }

      if (BufferG2D == null) {
        BufferG2D = img.createGraphics();
        BufferG2D.setRenderingHint(
            RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_DEFAULT);
        BufferG2D.setClip(clippath);
      }
      g2d = BufferG2D;

      float[] ctrlpts;
      for (int i = 0; i < animpts.length; i += 2) {
        animate(animpts, deltas, i + 0, size.width);
        animate(animpts, deltas, i + 1, size.height);
      }
      ctrlpts = animpts;
      int len = ctrlpts.length;
      gp.reset();
      int dir = 0;
      float prevx = ctrlpts[len - 2];
      float prevy = ctrlpts[len - 1];
      float curx = ctrlpts[0];
      float cury = ctrlpts[1];
      float midx = (curx + prevx) / 2.0f;
      float midy = (cury + prevy) / 2.0f;
      gp.moveTo(midx, midy);
      for (int i = 2; i <= ctrlpts.length; i += 2) {
        float x1 = (midx + curx) / 2.0f;
        float y1 = (midy + cury) / 2.0f;
        prevx = curx;
        prevy = cury;
        if (i < ctrlpts.length) {
          curx = ctrlpts[i + 0];
          cury = ctrlpts[i + 1];
        } else {
          curx = ctrlpts[0];
          cury = ctrlpts[1];
        }
        midx = (curx + prevx) / 2.0f;
        midy = (cury + prevy) / 2.0f;
        float x2 = (prevx + midx) / 2.0f;
        float y2 = (prevy + midy) / 2.0f;
        gp.curveTo(x1, y1, x2, y2, midx, midy);
      }
      gp.closePath();

      g2d.setComposite(set);
      g2d.setBackground(backgroundColor);
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);

      if (bgChanged || bounds == null) {
        bounds = new Rectangle(0, 0, getWidth(), getHeight());
        bgChanged = false;
      }
      // g2d.clearRect(bounds.x-5, bounds.y-5, bounds.x + bounds.width + 5, bounds.y + bounds.height
      // + 5);
      g2d.clearRect(0, 0, getWidth(), getHeight());

      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      g2d.setColor(outerColor);
      g2d.setComposite(opaque);
      g2d.setStroke(solid);
      g2d.draw(gp);
      g2d.setPaint(gradient);

      if (!bgChanged) {
        bounds = gp.getBounds();
      } else {
        bounds = new Rectangle(0, 0, getWidth(), getHeight());
        bgChanged = false;
      }
      gradient =
          new GradientPaint(
              bounds.x,
              bounds.y,
              gradientColorA,
              bounds.x + bounds.width,
              bounds.y + bounds.height,
              gradientColorB,
              true);
      g2d.setComposite(blend);
      g2d.fill(gp);

      if (g2d == BufferG2D) {
        repaint();
      }
      ++frame;
      Thread.yield();
    }
    if (g2d != null) {
      g2d.dispose();
    }
  }
Пример #23
0
  /**
   * waitForConnection waits for incomming connections. There are two cases. If we receive a
   * JoinNetworkRequest it means that a new peer tries to get into the network. We lock the entire
   * system, and sends a ConnectionData object to the new peer, from which he can connect to every
   * other peer. We add this new peer to our data.
   *
   * <p>If we receive a NewPeerDataRequest, it means that a new peer has received ConnectionData
   * from another peer in the network, and he is now trying to connect to everyone, including me. We
   * then update our data with the new peer.
   */
  private void waitForConnection() {
    while (active) {
      Socket client = waitForConnectionFromClient();
      if (client != null) {
        try {
          ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
          ObjectInputStream input = new ObjectInputStream(client.getInputStream());
          Object o = input.readObject();

          if (o instanceof JoinNetworkRequest) {
            JoinNetworkRequest request = (JoinNetworkRequest) o;
            dec.sendObjectToAllPeers(new LockRequest(lc.getTimeStamp()));
            waitForAllToLock();
            setLocked(true);
            Thread.sleep(500);
            int id = getNewId();
            Peer p =
                new Peer(
                    editor,
                    er,
                    id,
                    client,
                    output,
                    input,
                    lc,
                    client.getInetAddress().getHostAddress(),
                    request.getPort());
            ConnectionData cd =
                new ConnectionData(
                    er.getEventHistory(),
                    er.getAcknowledgements(),
                    er.getCarets(),
                    id,
                    area1.getText(),
                    lc.getTimeStamp(),
                    lc.getID(),
                    dec.getPeers(),
                    serverSocket.getLocalPort());
            p.writeObjectToStream(cd);
            dec.addPeer(p);
            Thread t = new Thread(p);
            t.start();
            er.addCaretPos(id, 0);
          } else if (o instanceof NewPeerDataRequest) {
            NewPeerDataRequest request = (NewPeerDataRequest) o;
            Peer newPeer =
                new Peer(
                    editor,
                    er,
                    request.getId(),
                    client,
                    output,
                    input,
                    lc,
                    client.getInetAddress().getHostAddress(),
                    request.getPort());
            dec.addPeer(newPeer);
            er.addCaretPos(request.getId(), request.getCaretPos());
            newPeer.writeObjectToStream(new NewPeerDataAcknowledgement(lc.getTimeStamp()));
            Thread t = new Thread(newPeer);
            t.start();
          }
        } catch (IOException | ClassNotFoundException | InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }
Пример #24
0
        public void actionPerformed(ActionEvent e) {
          saveOld();
          final InetAddress local;
          active = true;
          try {
            local = InetAddress.getLocalHost();
            Runnable server =
                new Runnable() {
                  public void run() {
                    serverport = Integer.parseInt(portNumber.getText());
                    int myID = getNewId();
                    registerOnPort();
                    editor.setTitleToListen();
                    clientSocket = waitForConnectionFromClient();
                    lc = new LamportClock(myID);
                    area1.setText("");
                    resetArea2();
                    if (clientSocket != null) {
                      listen = true;
                      connected = true;
                      dec = new DocumentEventCapturer(lc, editor);
                      setDocumentFilter(dec);
                      er = new EventReplayer(editor, dec, lc);
                      er.updateCaretPos(myID, 0);
                      ert = new Thread(er);
                      ert.start();

                      try {
                        ObjectOutputStream output =
                            new ObjectOutputStream(clientSocket.getOutputStream());
                        ObjectInputStream input =
                            new ObjectInputStream(clientSocket.getInputStream());
                        JoinNetworkRequest request = (JoinNetworkRequest) input.readObject();
                        int id = getNewId();
                        Peer peer =
                            new Peer(
                                editor,
                                er,
                                id,
                                clientSocket,
                                output,
                                input,
                                lc,
                                clientSocket.getInetAddress().getHostAddress(),
                                request.getPort());
                        ConnectionData cd =
                            new ConnectionData(
                                er.getEventHistory(),
                                er.getAcknowledgements(),
                                er.getCarets(),
                                id,
                                area1.getText(),
                                lc.getTimeStamp(),
                                lc.getID(),
                                dec.getPeers(),
                                serverSocket.getLocalPort());
                        dec.addPeer(peer);
                        er.addCaretPos(id, 0);
                        Thread t = new Thread(peer);
                        t.start();
                        peer.writeObjectToStream(cd);
                      } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                      }
                    }
                    waitForConnection();
                  }
                };
            Thread serverThread = new Thread(server);
            serverThread.start();
          } catch (UnknownHostException e1) {
            e1.printStackTrace();
          }

          changed = false;
          Disconnect.setEnabled(true);
          Listen.setEnabled(false);
          Connect.setEnabled(false);
          Save.setEnabled(false);
          SaveAs.setEnabled(false);
        }
Пример #25
0
  public static void main(String[] args) {
    if (args.length > 0) {
      try {
        if (args[0].equals("-stress")) {
          String userName = args[1];
          String server = args[2];
          String targetUser = args[3];
          int rate = Integer.parseInt(args[4]);
          Session session = new Session();
          if (session.connect(server, userName)) {
            long msgCount = 0;
            while (true) {
              for (int i = 0; i < rate; i++) {
                msgCount++;
                session.postMessage(
                    targetUser, ("subject " + String.valueOf(msgCount)), Util.randomString(1000));
              }
              Thread.currentThread().sleep(2000);
            }
          }
        } else if (args[0].equals("-stress2")) {
          String userName = args[1];
          String server = args[2];
          String targetUser = args[3];
          int rate = Integer.parseInt(args[4]);
          Session session = new Session();
          long msgCount = 0;
          while (true) {
            if (session.connect(server, userName)) {
              for (int i = 0; i < rate; i++) {
                msgCount++;
                session.postMessage(
                    targetUser, ("subject " + String.valueOf(msgCount)), Util.randomString(1000));
              }
              session.disconnect();
            }
            Thread.currentThread().sleep(2000);
          }

        } else if (args[0].equals("-stress3")) {
          String userName = args[1];
          String server = args[2];
          String targetUser = args[3];
          int rate = Integer.parseInt(args[4]);
          Session session = new Session();
          long msgCount = 0;
          while (true) {
            if (session.connect(server, userName)) {
              for (int i = 0; i < rate; i++) {
                msgCount++;
                session.postMessage(
                    targetUser, ("subject " + String.valueOf(msgCount)), Util.randomString(1000));
              }
              session.dropConnection();
            }
            Thread.currentThread().sleep(2000);
          }
        } else if (args[0].equals("-stress4")) {
          String userName = args[1];
          String server = args[2];
          String targetUser = args[3];
          int rate = Integer.parseInt(args[4]);
          Session session = new Session();
          long msgCount = 0;
          while (true) {
            if (session.connect(server, userName)) {
              for (int i = 0; i < rate; i++) {
                msgCount++;
                session.postMessage(
                    targetUser, ("subject " + String.valueOf(msgCount)), Util.fixedString(300000));
              }
              session.dropConnection();
            }
            Thread.currentThread().sleep(5000);
          }

        } else if (args[0].equals("-stress5")) {
          String userName = args[1];
          String server = args[2];
          String targetUser = args[3];
          int rate = Integer.parseInt(args[4]);
          Session session = new Session();
          if (session.connect(server, userName)) {
            long msgCount = 0;
            while (true) {
              for (int i = 0; i < rate; i++) {
                msgCount++;
                session.postMessage(
                    targetUser, ("subject " + String.valueOf(msgCount)), Util.randomString(10));
              }
              Thread.currentThread().sleep(2000);
            }
          }
        } else if (args[0].equals("-monitor")) {
          String userName = args[1];
          String server = args[2];
          long interval = Long.parseLong(args[3]);
          Session session = new Session();
          long msgCount = 0;
          if (session.connect(server, userName)) {
            while (true) {
              Message msg = session.sendMessage("", "get send queue stats", "");
              System.out.println("SEND QUEUE STATS");
              System.out.println(msg.getBody());
              Thread.currentThread().sleep(interval);
            }
          }
        } else if (args[0].equals("-responder")) {
          String userName = args[1];
          String server = args[2];
          long interval = Long.parseLong(args[3]);
          final Session session = new Session();
          if (session.connect(server, userName)) {
            session.addListener(
                new AsyncMessageReceiverListener() {
                  public void receiveMsg(Message msg) {
                    session.postMessage(
                        msg.getFrom(), "RE: " + msg.getFrom(), msg.getThread(), msg.getBody());
                  }

                  public void messageReceiverClosed(MessageReceiver mr) {}
                });
            while (true) {
              Thread.currentThread().sleep(interval);
            }
          }
        } else if (args[0].equals("-threaded-sender")) {
          String userName = args[1];
          String server = args[2];
          String targetUser = args[3];
          int rate = Integer.parseInt(args[4]);
          Session session = new Session();
          long msgCount = 0;
          if (session.connect(server, userName)) {
            while (true) {
              for (int i = 0; i < rate; i++) {
                msgCount++;
                Message reply =
                    session.sendMessage(
                        targetUser, ("subject " + String.valueOf(msgCount)), "body", 10000);
                if (reply == null) {
                  System.out.println("reply not received");
                }
              }
              Thread.currentThread().sleep(5000);
            }
          }
        }
      } catch (Exception e) {
        System.out.println(
            "Unable to start stress test.  Format: -stress <user name> <server> <target user> <msg rate>");
      }
    } else {
      Client client = new Client();
      client.setSize(800, 420);
      center(client);
      client.show();
    }
  }