public static void main(String args[]) {
    DatagramSocket skt = null;
    try {
      skt = new DatagramSocket(6789);
      byte[] buffer = new byte[1000];
      while (true) {
        DatagramPacket request = new DatagramPacket(buffer, buffer.length);
        skt.receive(request);
        System.out.println("Data received from client");
        System.out.println(new String(request.getData()));
        Thread.sleep(15000);

        String[] arrayMsg = (new String(request.getData())).split(" ");

        System.out.println(arrayMsg[0] + "server processed");

        byte[] sendMsg = (arrayMsg[0] + "server processed").getBytes();

        DatagramPacket reply =
            new DatagramPacket(sendMsg, sendMsg.length, request.getAddress(), request.getPort());

        System.out.println("sending data from server to client");
        Thread.sleep(15000);
        ;
        skt.send(reply);
      }
    } catch (Exception e) {

    }
  }
Beispiel #2
0
  public static void main(String[] args) throws LBMException {
    LBMContext ctx = null; /* Context object: container for UM "instance". */
    LBMSource src = null; /* Source object: for sending messages. */

    SrcCB srccb = new SrcCB();

    /** * Initialization: create necessary UM objects. ** */
    try {
      LBMTopic topic = null;
      LBMSourceAttributes srcAttr = null;

      ctx = new LBMContext();
      srcAttr = new LBMSourceAttributes();
      srcAttr.setValue("ume_store", "127.0.0.1:29999");
      srcAttr.setValue("ume_store_behavior", "qc");
      topic = ctx.allocTopic("test.topic", srcAttr);
      src = ctx.createSource(topic, srccb, null, null);
    } catch (LBMException ex) {
      System.err.println("Error initializing LBM objects: " + ex.toString());
      System.exit(1);
    }

    while (true) {
      if (srcReady == 1) {
        /** * Send a message. ** */
        try {
          src.send("test".getBytes(), "test".getBytes().length, LBM.MSG_FLUSH | LBM.SRC_NONBLOCK);
        } catch (LBMException ex) {
          /* Error trying to send, wait 1 second and try again */
          try {
            Thread.sleep(1000);
          } catch (InterruptedException tex) {
            System.err.println("Error Thread.sleep interrupted: " + tex.toString());
            System.exit(1);
          }
        }
      } else {
        /* No quorum, wait 1 second and check again */
        System.out.println("Source is not ready to send (no quorum)");
        try {
          Thread.sleep(1000);
        } catch (InterruptedException tex) {
          System.err.println("Error Thread.sleep interrupted: " + tex.toString());
          System.exit(1);
        }
      }
    }
  } /* main */
  @Override
  public void run() {
    Log.d(MeerkatApplication.TAG, "\tAbstractPeriodicDataSource.run");
    try {
      while (mRun) {
        if (!mTickLock) {
          mTickLock = true;

          // [FIXME: is there a better way to protect against mRun
          // being unset during sleep?]
          if (mRun) {
            // execute the main task of the thread
            tick();
          }

          mTickLock = false;
        }

        // sleep for mPeriodMs milliseconds
        Thread.sleep(mPeriodMs);
      }
    } catch (InterruptedException ex) {
      Log.i(MeerkatApplication.TAG, "AbstractPeriodicDataSource: run: interrupted");
    }
  }
  public void testRefreshRate() throws java.lang.InterruptedException {
    boolean fpsOk = false;
    GLSurfaceViewStubActivity activity = getActivity();

    WindowManager wm =
        (WindowManager) activity.getView().getContext().getSystemService(Context.WINDOW_SERVICE);
    Display dpy = wm.getDefaultDisplay();
    float claimedFps = dpy.getRefreshRate();

    for (int i = 0; i < 3; i++) {
      float achievedFps = mResult.waitResult();
      Log.d(TAG, "claimed " + claimedFps + " fps, " + "achieved " + achievedFps + " fps");
      fpsOk = Math.abs(claimedFps - achievedFps) <= FPS_TOLERANCE;
      if (fpsOk) {
        break;
      } else {
        // it could be other sctivity like bug report capturing for other failures
        // sleep for a while and re-try
        Thread.sleep(10000);
        mResult.restart();
      }
    }
    activity.finish();
    assertTrue(fpsOk);
  }
Beispiel #5
0
 public static void main(String[] args) throws Exception {
   long start = System.currentTimeMillis();
   java.lang.Thread.sleep(1000);
   if (1000 <= System.currentTimeMillis() - start) {
     System.out.println("slept");
   }
 }
Beispiel #6
0
  // only works locally.
  void enterCommandMode() throws ZigBeeException, SerialException {
    if (serialPort == null) {
      serialPort = new Serial();
    }
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
    }

    serialPort.addListener(null);

    String s = new String("+++");
    serialPort.write(s);

    do {
      s = serialPort.waitForData(1500);

      if (s != null) {
        if (s.indexOf("OK") >= 0) {
          return;
        }
      }
    } while (s != null);

    close();
    throw new ZigBeeException("Unable to enter command mode.");
  }
  @Test
  public void testCreateAndTimeoutTransaction() throws IOException, InterruptedException {

    /* create a short-lived tx */
    final long testTimeout = min(500, REAP_INTERVAL / 2);
    System.setProperty(TIMEOUT_SYSTEM_PROPERTY, Long.toString(testTimeout));

    /* create a tx */
    final String location = createTransaction();

    try (CloseableHttpResponse resp = execute(new HttpGet(location))) {
      assertEquals(OK.getStatusCode(), getStatus(resp));
      assertTrue(
          stream(resp.getHeaders(LINK))
              .anyMatch(i -> i.getValue().contains("<" + serverAddress + ">;rel=\"canonical\"")));
      consume(resp.getEntity());
    }

    sleep(REAP_INTERVAL * 2);
    try {
      assertEquals(
          "Transaction did not expire", GONE.getStatusCode(), getStatus(new HttpGet(location)));
    } finally {
      System.setProperty(TIMEOUT_SYSTEM_PROPERTY, DEFAULT_TIMEOUT);
      System.clearProperty("fcrepo.transactions.timeout");
    }
  }
 public static void wait(DatagramSocket skt, DatagramPacket request)
     throws IOException, InterruptedException {
   // stop till you receive
   skt.receive(request);
   System.out.println("request received");
   Thread.sleep(2000);
 }
 private void sleepBecauseWindowsTakeTimeToOpen() {
   try {
     sleep(1000);
   } catch (InterruptedException e) {
     fail("Interrupted");
   }
 }
  public static void main(String[] args) throws InterruptedException, IOException {
    System.setProperty("java.net.preferIPv4Stack", "true");
    TransactionProcessor transProcessor = new TransactionProcessor();
    transProcessor.getId();
    System.out.println(
        "Transaction Processor id " + transProcessor.id + " waiting to be activated");
    new Thread() {
      public void run() {
        for (int i = 0; i < 4; i++) {
          transProcessor.updatePeers(transProcessor.id, 0);
          try {
            sleep(peersUpdateInterval);
          } catch (InterruptedException ex) {
            Logger.getLogger(TransactionProcessor.class.getName()).log(Level.SEVERE, null, ex);
          }
        }
      }
    }.start();

    transProcessor.listenMulticast();

    Thread t = new Thread(transProcessor);
    t.setUncaughtExceptionHandler(transProcessor.h);
    t.start();
    while (true) {
      transProcessor.sendAliveSignal();
      Thread.sleep(transProcessor.sendingInverval);
    }
  }
  public void killApp() throws Exception {
    // try to kill just by calling exit
    try {
      Client.getInstance().map("java.lang.System", "exit", 0);
    } catch (Exception e) {
      // this will actually throw an exception since it doesnt get a response from this command
    }

    // shut down the thread
    if (ap != null) {
      ap.close();
      ap.interrupt();
      ap = null;
    }

    // wait for the server to be dead
    for (int x = 0; x < 10; x++) {
      // try to make a query.. if it doesnt work then sleep
      TestLogger.get().info("Trying to see if server is still available..");

      if (!Client.getInstance().isListening()) break;

      if (x == 9) throw new Exception("Server is still available, but should not be");

      Thread.sleep(2000);
    }
  }
  public static void main(String[] args) throws Exception {

    IPhoneDriver driver = new IPhoneDriver("http://192.168.0.39:3001/hub/");

    driver.get("http://orangeworld.co.uk/");
    System.out.println(driver.getCurrentUrl());

    WebElement MenuTab = driver.findElementByXPath(Constants.MenuTab);
    MenuTab.isDisplayed();
    MenuTab.click();
    Thread.sleep(3000);
    // Menu Content Entertainment
    WebElement MenuContent_Entertainment =
        driver.findElementByXPath(Constants.MenuContent_Entertainment);
    MenuContent_Entertainment.isDisplayed();
    MenuContent_Entertainment.click();

    WebElement MenuContent_Entertainment_BreadCrumb =
        driver.findElementByXPath(Constants.MenuContent_Entertainment_BreadCrumb);
    MenuContent_Entertainment_BreadCrumb.isDisplayed();
    System.out.println("BreadCrumb Name is " + MenuContent_Entertainment_BreadCrumb.getText());

    WebElement Entertainment_Homepage = driver.findElementByXPath(Constants.Entertainment_Homepage);
    Entertainment_Homepage.isDisplayed();
    Entertainment_Homepage.click();
    System.out.println(driver.getCurrentUrl());

    System.out.println("Test pass");

    driver.quit();
  }
Beispiel #13
0
  public void run() {
    java.io.File[] logFileList;
    int logs_to_keep = 3;
    int minlog;

    for (; ; ) {
      /*
       * Wait for one minute, polling once per second to see if
       * application has finished.  When application has finished,
       * terminate this thread.
       */
      for (int i = 0; i < 60; i++) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException ie) {
        }
        if (myEnv.getAppFinished()) return;
      }

      try {
        /* Get the list of unneeded log files. */
        logFileList = myEnv.getArchiveLogFiles(false);
        /*
         * Remove all but the logs_to_keep most recent unneeded
         * log files.
         */
        minlog = logFileList.length - logs_to_keep;
        for (int i = 0; i < minlog; i++) {
          logFileList[i].delete();
        }
      } catch (DatabaseException de) {
        System.err.println("Problem deleting log archive files.");
      }
    }
  }
Beispiel #14
0
  public static void main(String args[]) throws Exception {
    // Making a text file
    String filename =
        "C:\\Users\\S.S. Mehta\\Desktop\\Codes\\ComputerNetworks\\CN_project\\CN_project\\test3.txt";
    makeTextFile(filename);

    // Reading the file and puttin it in buffer
    BufferedReader in = new BufferedReader(new FileReader(filename));
    char[] c1 = new char[PACKET_SIZE];
    c1 = readData(in);
    displayPacket(c1);

    // Step3 - making a socket , makeing a packet with inet address and sending it
    byte[] buffer = new byte[PACKET_SIZE];
    DatagramSocket skt = new DatagramSocket(PORT_NUMBER);
    DatagramPacket request = new DatagramPacket(buffer, buffer.length);

    // stop till you receive
    wait(skt, request);
    System.out.println("On server side \nrequest received from Slient");
    // making a packet with an inet address -
    InetAddress host = InetAddress.getByName("localhost");

    DatagramPacket reply = makePacket(c1, host);

    // Sending reply packet
    System.out.println("Sending reply packet to client");
    Thread.sleep(5000);
    skt.send(reply);

    // closing the socket
    skt.close();
  }
Beispiel #15
0
  private boolean connectSPPMon() {
    if (state == ConnectionEvent.CONNECTION_PENDING) {
      ExpCoordinator.print(
          new String("NCCPConnection(" + host + ", " + port + ").connect connection pending"), 0);
      while (state == ConnectionEvent.CONNECTION_PENDING) {
        try {
          Thread.sleep(500);
        } catch (java.lang.InterruptedException e) {
        }
      }
      return (isConnected());
    }

    state = ConnectionEvent.CONNECTION_PENDING;
    if (nonProxy != null) {
      try {
        nonProxy.connect();
      } catch (UnknownHostException e) {
        boolean rtn = informUserError("Don't know about host: " + host + ":" + e.getMessage());
        return rtn;
      } catch (SocketTimeoutException e) {
        boolean rtn = informUserError("Socket time out for " + host + ":" + e.getMessage());
        return rtn;
      } catch (IOException e) {
        boolean rtn = informUserError("Couldnt get I/O for " + host + ":" + e.getMessage());
        return rtn;
      }
    }
    return (isConnected());
  }
 public static void sleep(long time) {
   try {
     java.lang.Thread.sleep(time);
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }
Beispiel #17
0
  /**
   * sleep some
   *
   * @param time
   */
  public void sleep(int time) {
    try {
      java.lang.Thread.sleep(time);
    } catch (InterruptedException e) {

    }
  }
Beispiel #18
0
  public void run() {
    PrintStream out = new PrintStream(outFile);
    DataInputStream in = new DataInputStream(inFile);
    try {
      while (!suspending) {

        String line = in.readLine();

        if (line == null) break;

        if (line.contains(query)) {
          out.println(line);
        }
        // Make grep take longer so that we don't require extremely
        // large files for interesting results
        try {
          Thread.sleep(2000);
        } catch (InterruptedException e) {
          // ignore it
        }
      }
    } catch (EOFException e) {
      // End of File
    } catch (IOException e) {
      System.out.println("GrepProcess: Error: " + e);
    }
    try {
      outFile.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      // e.printStackTrace();
    }
    out.close();
    suspending = false;
  }
 @Test
 public void testThatCountsExactlyOneSubmittedRequest() throws Exception {
   executorService.submit(new MockTextQuery(), Optional.empty());
   executorService.submit(new MockTextQuery(), Optional.empty());
   executorService.submit(new MockTextQuery(), Optional.empty());
   sleep(MockTextProvider.FETCH_DELAY / 2);
   assertEquals(1, executorService.countSubmitted());
 }
 @Test(timeout = 60000, expected = IllegalStateException.class)
 public void testThatCanNotSubmitWhenInShutdownState() throws Exception {
   new Thread(
           () -> {
             try {
               sleep(1000);
               executorService.shutdown();
             } catch (InterruptedException ignored) {
             }
           })
       .start();
   for (int i = 0; i < 10; i++) {
     executorService.submit(new MockTextQuery(), Optional.empty());
     sleep(MockTextProvider.FETCH_DELAY / 2);
   }
   assertTrue("service is not allowed to accept submissions after shutdown", false);
 }
  /**
   * This is the generic test setup function
   *
   * @param relaunch - true if this is an app relaunch
   * @param clearAppData - true if you want app data cleared, false otherwise
   */
  public static void setUp(String testName, Boolean relaunch, Boolean clearAppData)
      throws Exception {
    if (!relaunch) {
      logger.info("Starting test {}", testName);
      Utils.setTestName(testName);
      Device.setupLogDirectories();

      // create adb tunnel
      DebugBridge.get().createTunnel(8080, 8080);
    }

    // see if a server is already listening
    boolean clientWasListening = false;
    if (Client.isListening()) {
      clientWasListening = true;
    }

    if (clearAppData) {
      // clear app data - this has the side effect of killing a running app
      // TODO: this only works on 2.3+.. need a solution for 2.1+
      Device.clearAppData();
    }

    // wait for the client to stop listening if it was previously listening
    if (clientWasListening) {
      // wait for the server to be dead
      for (int x = 0; x < 10; x++) {
        // try to make a query.. if it doesnt work then sleep
        TestLogger.get().info("Trying to see if server is still available..");

        if (!Client.isListening()) break;

        if (x == 9) throw new Exception("Server is still available, but should not be");

        Thread.sleep(2000);
      }
    }

    if (!relaunch) {
      // start log listener
      TestLogger.get().info("Clearing logcat");
      DebugBridge.get().clearLogCat();

      TestLogger.get().info("Starting logcat");
      DebugBridge.get().startLogListener("/tmp/adb_robo.log");

      // set up logger
      EmSingleton.intialize();

      EmSingleton.get().clearEvents();
    }

    // starting test runner
    TestLogger.get().info("Starting RC Runner");

    // start app
    Device.startApp();
  }
 @Test(timeout = 60000)
 public void testThatInProgressTaskCountWell() throws Exception {
   MockTextQuery query1 = new MockTextQuery();
   MockTextQuery query2 = new MockTextQuery();
   executorService.submit(query1, Optional.empty());
   executorService.submit(query2, Optional.empty());
   sleep(MockTextProvider.FETCH_DELAY / 2);
   assertEquals(2, this.executorService.countInProgress());
 }
 public void run() {
   while (true) {
     try {
       Thread.sleep(interval);
     } catch (InterruptedException ignore) {
     }
     stepTimeout();
   }
 }
Beispiel #24
0
  // 为了随时判断,把hitTank函数摆在这里(随时刷新)
  @Override
  public void run() {
    // 每隔50ms 重绘制
    while (true) {
      try {
        Thread.sleep(10);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      // 判断击中敌人坦克
      this.hitEnemyTank();
      // 判断敌人子弹是否击中我方坦克的函数
      this.hitMe();

      //            //判断是否需要给坦克加入新的子弹
      //            for(int i=0;i<enemyTanks.size();i++)
      //            {
      //                EnemyTank et=enemyTanks.get(i);
      //                if (et.alive)
      //                {
      //                    if(et.bb.size()<5){
      //                        //没有子弹
      //                        //添加
      //                        System.out.println("et.bb.size()<5="+et.bb.size());
      //                        Bullet b=null;
      //                        switch (et.direct)
      //                        {
      //                            case 0:
      //                                //创建一颗子弹,把子弹加入到向量
      //                                b=new Bullet(et.x+10,et.y,0);
      //                                et.bb.add(b);
      //                                break;
      //                            case 1:
      //                                b=new Bullet(et.x+30,et.y+10,1);
      //                                et.bb.add(b);
      //                                break;
      //                            case 2:
      //                                b=new Bullet(et.x+10,et.y+30,2);
      //                                et.bb.add(b);
      //                                break;
      //                            case 3:
      //                                b=new Bullet(et.x,et.y+10,3);
      //                                et.bb.add(b);
      //                                break;
      //
      //                        }
      //
      //                        //启动子弹线程
      //                        Thread t =new Thread(b);
      //                        t.start();
      //                    }
      //                }
      //            }

      this.repaint();
    }
  }
Beispiel #25
0
  /**
   * sleep some
   *
   * @param time
   */
  public void sleep(long time) {
    try {
      java.lang.Thread.sleep(time / 1000000);
    } catch (InterruptedException e) {

    } catch (IllegalArgumentException e) {

    }
  }
 public void callMain(String args[]) {
   try {
     Thread.sleep(60000);
   } catch (Exception eee) {
   }
   for (int i = 0; i < 10; i++) {
     testUpdateNode();
     testAddUpdateDeleteNode();
   }
 }
Beispiel #27
0
  // We need in this constructor to pass frame position between JVMs
  public FileListBetweenJVMsTest(
      Point targetFrameLocation, Point dragSourcePoint, int transferredFilesNumber)
      throws InterruptedException {
    TargetFileListFrame targetFrame =
        new TargetFileListFrame(targetFrameLocation, transferredFilesNumber);

    Util.waitForIdle(null);

    final Robot robot = Util.createRobot();

    robot.mouseMove((int) dragSourcePoint.getX(), (int) dragSourcePoint.getY());
    sleep(100);
    robot.mousePress(InputEvent.BUTTON1_MASK);
    sleep(100);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    sleep(100);

    Util.drag(robot, dragSourcePoint, targetFrame.getDropTargetPoint(), InputEvent.BUTTON1_MASK);
  }
 private void waitIndefinitely() {
   while (true) {
     try {
       sleep(MAX_VALUE);
     } catch (InterruptedException e) {
       interrupted();
       // meh
     }
   }
 }
 @Test(timeout = 60000)
 public void testThatShutdownMethodWaitsAllCurrentTask() throws Exception {
   MockTextQuery request1 = new MockTextQuery();
   MockTextQuery request2 = new MockTextQuery();
   executorService.submit(request1, Optional.empty());
   executorService.submit(request2, Optional.empty());
   sleep(MockTextProvider.FETCH_DELAY / 2);
   executorService.shutdown();
   assertEquals(0, this.executorService.countInProgress());
 }
 @Override
 public void run() {
   while (true) {
     closeUnusedWebdrivers();
     try {
       Thread.sleep(100);
     } catch (InterruptedException e) {
       Thread.currentThread().interrupt();
       break;
     }
   }
 }