/**
   * @param args
   * @throws InterruptedException
   */
  public static void main(String[] args) throws InterruptedException {

    Thread t1 =
        new Thread() {
          @Override
          public void run() {
            long i = 0l;
            try {

              while (this.isInterrupted() == false) {
                System.out.println(Thread.currentThread().getName() + " sleep 10 ");
                TimeUnit.SECONDS.sleep(10);
              }
            } catch (InterruptedException e) // 会抛出InterruptException因为Sleep会阻塞
            {
              e.printStackTrace();
              System.out.println(Thread.currentThread().getName() + ":" + e.getMessage());
            }
          }
        };

    Thread t2 =
        new Thread() {
          @Override
          public void run() {
            long i = 0l;
            while (this.isInterrupted() == false) {
              try {
                Thread.currentThread().sleep(1);
                i++;
                while (true) {
                  i++;
                }
              } catch (InterruptedException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
              }
            }
          }
        };

    t1.start();
    t2.start();

    System.out.println(
        t1.getName() + " before interupt:" + t1.isInterrupted() + "   is alive=" + t1.isAlive());
    System.out.println(
        t2.getName() + " before interupt:" + t2.isInterrupted() + "   is alive=" + t2.isAlive());
    TimeUnit.SECONDS.sleep(1);
    t1.interrupt();
    t2.interrupt();
    TimeUnit.SECONDS.sleep(1);
    System.out.println(
        t1.getName() + " after interupt:" + t1.isInterrupted() + "   is alive=" + t1.isAlive());
    System.out.println(
        t2.getName() + " after interupt:" + t2.isInterrupted() + "   is alive=" + t2.isAlive());
  }
  public String addNewProject(String projectName) throws InterruptedException {

    WebElement btnNewProj =
        driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.id("new_project")));

    btnNewProj.click();
    TimeUnit.SECONDS.sleep(2);

    executeJavascript("document.getElementsByClassName('edit_me')[0].click();");
    TimeUnit.SECONDS.sleep(2);

    WebElement txtName = getWebDriver().findElement(By.id("projects_project_title"));
    txtName.click();
    txtName.clear();
    txtName.sendKeys(projectName);

    List<WebElement> saveBtnList =
        getWebDriver().findElements(By.xpath(".//*[@id='projects_project_submit_action']/input"));
    for (WebElement btnSave : saveBtnList) {
      if (btnSave.isDisplayed()) btnSave.click();
    }

    TimeUnit.SECONDS.sleep(1);
    String name = "";
    List<WebElement> txtist = getWebDriver().findElements(By.cssSelector(".element-plain-text"));
    for (WebElement title : txtist) {
      if (title.getText().equals(projectName)) {
        name = title.getText();
        break;
      }
    }
    return name;
  }
Esempio n. 3
0
  @Test
  public void testSendAllIntersesst() throws Exception {
    /*
    All should be exchanged but not direction 0
     */

    try {
      TimeUnit.SECONDS.sleep(15);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    bob.newsKP.sendAllIntersesst(alicepeer);
    try {
      TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    Vector allnews = bob.newsKP.getNews();
    Assert.assertTrue(allnews.contains("Supernews"));
    Assert.assertTrue(allnews.contains("Sportnews"));
    Assert.assertTrue(allnews.contains("Fussballnews"));
    Assert.assertFalse(allnews.contains("Politiknews"));
    Assert.assertFalse(allnews.contains("foo"));
  }
  private String addFolderAction(String folderToCreate) throws InterruptedException {

    TimeUnit.SECONDS.sleep(2);

    executeJavascript("document.getElementsByClassName('edit_me')[0].click();");
    TimeUnit.SECONDS.sleep(2);

    WebElement txtName = getWebDriver().findElement(By.id("projects_milestone_title"));
    txtName.click();
    txtName.clear();
    txtName.sendKeys(folderToCreate);

    List<WebElement> saveBtnList =
        getWebDriver().findElements(By.xpath(".//*[@id='projects_milestone_submit_action']/input"));
    for (WebElement btnSave : saveBtnList) {
      if (btnSave.isDisplayed()) btnSave.click();
    }

    TimeUnit.SECONDS.sleep(1);
    String name = "";
    List<WebElement> txtist = getWebDriver().findElements(By.cssSelector(".element-plain-text"));
    for (WebElement title : txtist) {
      if (title.getText().equals(folderToCreate)) {
        name = title.getText();
        break;
      }
    }
    return name;
  }
Esempio n. 5
0
  /*
   * (non-Javadoc)
   *
   * @see java.lang.Thread#run()
   */
  public void run() {
    try {
      while (true) {
        if (Manager.instance().canDump()) {
          Manager.instance().setProfileFlag(true);
          TimeUnit.SECONDS.sleep(eachProfUseTime);
          Manager.instance().setProfileFlag(false);
          // 等待已开始的End方法执行完成
          TimeUnit.MILLISECONDS.sleep(500L);

          dumpProfileData();
        }
        TimeUnit.SECONDS.sleep(eachProfIntervalTime);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      Manager.instance().setProfileFlag(false);
      if (fileWriter != null) {
        fileWriter.closeFile();
      }
      // 等待已开始的End方法执行完成
      try {
        TimeUnit.MILLISECONDS.sleep(500L);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      Profiler.clearData();
    }
  }
  @Test
  public void oneOfAtomDssInGropuIsOkTest() throws Exception {
    // 改变group中的rw状态(确保推送成功)
    for (int i = 0; i < 2; i++) {
      MockServer.setConfigInfo(
          tds.getFullDbGroupKey(),
          "qatest_normal_0:NA,qatest_normal_0_bac:r,qatest_normal_1_bac:r");
      TimeUnit.SECONDS.sleep(SLEEP_TIME);
    }

    int successCnt = 0;
    for (int i = 0; i < 20; i++) {
      tddlJT.queryForList(sql);
      successCnt++;
    }
    Assert.assertEquals(20, successCnt);

    // qatest_normal_0状态改为只读(确保推送成功)
    for (int i = 0; i < 2; i++) {
      MockServer.setConfigInfo(
          TAtomConstants.getGlobalDataId(DBKEY_0),
          "ip=10.232.31.154\r\nport=3306\r\ndbName=qatest_normal_0\r\ndbType=mysql\r\ndbStatus=NA");
      MockServer.setConfigInfo(
          tds.getFullDbGroupKey(),
          "qatest_normal_0:wr,qatest_normal_0_bac:r,qatest_normal_1_bac:r");
      TimeUnit.SECONDS.sleep(SLEEP_TIME);
    }

    successCnt = 0;
    for (int i = 0; i < 20; i++) {
      tddlJT.queryForList(sql);
      successCnt++;
    }
    Assert.assertEquals(20, successCnt);
  }
  @Test
  public void testMod() throws Exception {
    final BrokerService brokerService = new BrokerService();
    startBroker(brokerService);
    assertTrue("broker alive", brokerService.isStarted());
    assertEquals("no network connectors", 0, brokerService.getNetworkConnectors().size());

    DiscoveryNetworkConnector nc = createNetworkConnector();
    javaConfigBroker.addNetworkConnector(nc);
    TimeUnit.SECONDS.sleep(SLEEP);

    assertEquals("one network connectors", 1, brokerService.getNetworkConnectors().size());

    // track the original
    NetworkConnector networkConnector = brokerService.getNetworkConnectors().get(0);
    assertEquals("network ttl is default", 1, networkConnector.getNetworkTTL());

    nc.setNetworkTTL(2);
    javaConfigBroker.updateNetworkConnector(nc);
    TimeUnit.SECONDS.sleep(SLEEP);
    assertEquals("still one network connectors", 1, brokerService.getNetworkConnectors().size());

    NetworkConnector modNetworkConnector = brokerService.getNetworkConnectors().get(0);
    assertEquals("got ttl update", 2, modNetworkConnector.getNetworkTTL());

    // apply again - ensure no change
    javaConfigBroker.updateNetworkConnector(nc);
    assertEquals("no new network connectors", 1, brokerService.getNetworkConnectors().size());
    assertSame("same instance", modNetworkConnector, brokerService.getNetworkConnectors().get(0));
  }
 @Override
 public void run() {
   System.out.printf("Client: Begin\n");
   for (int i = 0; i < 3; i++) {
     for (int j = 0; j < 5; j++) {
       StringBuilder request = new StringBuilder();
       request.append("(");
       request.append(i);
       request.append("--");
       request.append(j);
       request.append(")");
       try {
         requestList.put(request.toString());
         TimeUnit.SECONDS.sleep(2);
       } catch (InterruptedException e) {
         e.printStackTrace();
       }
     }
     try {
       TimeUnit.SECONDS.sleep(2);
     } catch (InterruptedException e) {
       e.printStackTrace();
     }
   }
   System.out.printf("Client: End\n");
 }
Esempio n. 9
0
  public ColumnFamilyStore testSingleSSTableCompaction(String strategyClassName) throws Exception {
    Keyspace keyspace = Keyspace.open(KEYSPACE1);
    ColumnFamilyStore store = keyspace.getColumnFamilyStore(CF_STANDARD1);
    store.clearUnsafe();
    store.metadata.gcGraceSeconds(1);
    store.setCompactionStrategyClass(strategyClassName);

    // disable compaction while flushing
    store.disableAutoCompaction();

    long timestamp = populate(KEYSPACE1, CF_STANDARD1, 0, 9, 3); // ttl=3s

    store.forceBlockingFlush();
    assertEquals(1, store.getSSTables().size());
    long originalSize = store.getSSTables().iterator().next().uncompressedLength();

    // wait enough to force single compaction
    TimeUnit.SECONDS.sleep(5);

    // enable compaction, submit background and wait for it to complete
    store.enableAutoCompaction();
    FBUtilities.waitOnFutures(CompactionManager.instance.submitBackground(store));
    while (CompactionManager.instance.getPendingTasks() > 0
        || CompactionManager.instance.getActiveCompactions() > 0) TimeUnit.SECONDS.sleep(1);

    // and sstable with ttl should be compacted
    assertEquals(1, store.getSSTables().size());
    long size = store.getSSTables().iterator().next().uncompressedLength();
    assertTrue("should be less than " + originalSize + ", but was " + size, size < originalSize);

    // make sure max timestamp of compacted sstables is recorded properly after compaction.
    assertMaxTimestamp(store, timestamp);

    return store;
  }
  public static void Start() throws InterruptedException {

    List<NewGPM> newGpmForGet = NewGPM.get(Admin.updateParameters.percentGetNew);
    for (NewGPM element : newGpmForGet) {
      if (!Admin.isBaseUpdaterThreadRun) return;
      DataExtraction.newGPM(element.idGpm);
    }
    TimeUnit.SECONDS.sleep(1);

    List<SqlRow> gpmForUpdateProfile =
        GPM.getIdGpmByLastProfile(Admin.updateParameters.percentUpdateProfiles);
    for (SqlRow element : gpmForUpdateProfile) {
      if (!Admin.isBaseUpdaterThreadRun) return;
      Long id = element.getLong("gpm");
      GPM gpm = GPM.findById(id);
      if (gpm != null) {
        DataExtraction.updateProfile(gpm);
      }
    }
    TimeUnit.SECONDS.sleep(1);

    List<SqlRow> gpmForUpdatePost =
        GPM.getIdGpmByLastPosts(Admin.updateParameters.percentUpdatePosts);
    for (SqlRow element : gpmForUpdatePost) {
      if (!Admin.isBaseUpdaterThreadRun) return;
      Long id = element.getLong("gpm");
      GPM gpm = GPM.findById(id);
      if (gpm != null) {
        DataExtraction.updateActivity(gpm, 100);
      }
    }
    TimeUnit.SECONDS.sleep(1);
  }
Esempio n. 11
0
 public boolean testTailLog(String testHandle) throws Exception {
   testHandle = Strings.nullToEmpty(testHandle).trim();
   if (testHandle.isEmpty()) {
     throw new IllegalArgumentException("TestHandle is required");
   }
   TestStatusRequest statusRequest = new TestStatusRequest(testHandle);
   TestStatusResponse statusResponse;
   do {
     TimeUnit.SECONDS.sleep(5);
     statusResponse = post(statusRequest, true);
   } while (Status.isPending(statusResponse.getTestStatus().getStatus()));
   long offset = 0;
   do {
     long length = statusResponse.getTestStatus().getLogFileLength();
     if (length > offset) {
       offset = printLogs(testHandle, offset);
     } else {
       TimeUnit.SECONDS.sleep(5);
     }
     statusResponse = post(statusRequest, true);
   } while (Status.isInProgress(statusResponse.getTestStatus().getStatus()));
   while (offset < statusResponse.getTestStatus().getLogFileLength()) {
     offset = printLogs(testHandle, offset);
   }
   Status.assertOKOrFailed(statusResponse.getTestStatus().getStatus());
   return Status.isOK(statusResponse.getTestStatus().getStatus());
 }
  public static void main(String[] args)
      throws InterruptedException, ExecutionException, TimeoutException {
    ExecutorService executor = Executors.newFixedThreadPool(5);
    CompletableFuture<String> task1 =
        CompletableFuture.supplyAsync(
            () -> {
              try {
                System.out.println(Thread.currentThread().getName() + ": firstTask");
                TimeUnit.SECONDS.sleep(2);
              } catch (Exception e) {
              }
              return "1";
            });
    CompletableFuture<String> task2 =
        CompletableFuture.supplyAsync(
            () -> {
              try {
                System.out.println(Thread.currentThread().getName() + ": secondTask");
                TimeUnit.SECONDS.sleep(3);
              } catch (Exception e) {
              }
              return "2";
            });
    // a new thread from the supplied executor will execute third task
    task1.acceptEitherAsync(
        task2,
        (x) -> {
          System.out.println(Thread.currentThread().getName() + ": thirdTask " + x);
        },
        executor);

    TimeUnit.SECONDS.sleep(5);
    System.out.println(Thread.currentThread().getName() + ": " + task1.get());
    executor.shutdown();
  }
  protected boolean addTable(WebElement procedureDescToolBar, String data)
      throws InterruptedException {

    boolean created;
    WebElement tableLoader = procedureDescToolBar.findElement(By.cssSelector(".grid.load"));
    tableLoader.click();

    TimeUnit.SECONDS.sleep(4);

    writeInTable(data);

    TimeUnit.SECONDS.sleep(2);

    WebElement imgSaveDesc =
        driverWait.until(
            ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".fa.fa-check")));
    imgSaveDesc.click();
    TimeUnit.SECONDS.sleep(4);

    driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".delete_me")));

    String value = readFromTable();

    WebElement tableArea =
        driverWait.until(
            ExpectedConditions.visibilityOfElementLocated(
                By.cssSelector(".inline_form_container.type_excel.spreadJS_activated")));

    created = ((tableArea != null) && (data.equals(value)));
    return created;
  }
  public boolean addNoteFromNotesTab(String note) throws InterruptedException {

    clickOnTab("tabs-notes-link");

    clickOnButton("add_note");
    TimeUnit.SECONDS.sleep(1);

    // open note dialog and add data in it
    getWebDriver().switchTo().activeElement();

    driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.id("new_projects_note")));

    WebElement title = getWebDriver().findElement(By.id("title"));
    title.sendKeys(note);

    writeInRedactor("This is a note description");

    WebElement save = getWebDriver().findElement(By.id("Save"));
    save.click();
    TimeUnit.SECONDS.sleep(2);

    getWebDriver().switchTo().activeElement();

    // wait until tab content appears again
    driverWait.until(ExpectedConditions.visibilityOfElementLocated(By.id("add_note")));

    return checkNoteInList(note);
  }
Esempio n. 15
0
  @Test
  public void useTransactionTest() throws Exception {
    // Performing admin operations to create dataset instance
    // keyValueTable is a system dataset module
    Id.DatasetInstance myTableInstance = Id.DatasetInstance.from(namespace, "myTable");
    dsFramework.addInstance("keyValueTable", myTableInstance, DatasetProperties.EMPTY);

    Assert.assertTrue(feedManager.createFeed(FEED1));
    try {
      Cancellable cancellable =
          notificationService.subscribe(
              FEED1,
              new NotificationHandler<String>() {
                private int received = 0;

                @Override
                public Type getNotificationType() {
                  return String.class;
                }

                @Override
                public void received(
                    final String notification, NotificationContext notificationContext) {
                  notificationContext.execute(
                      new TxRunnable() {
                        @Override
                        public void run(DatasetContext context) throws Exception {
                          KeyValueTable table = context.getDataset("myTable");
                          table.write("foo", String.format("%s-%d", notification, received++));
                        }
                      },
                      TxRetryPolicy.maxRetries(5));
                }
              });
      TimeUnit.SECONDS.sleep(2);

      try {
        notificationService.publish(FEED1, "foobar");
        // Waiting for the subscriber to receive that notification
        TimeUnit.SECONDS.sleep(2);

        KeyValueTable table =
            dsFramework.getDataset(myTableInstance, DatasetDefinition.NO_ARGUMENTS, null);
        Assert.assertNotNull(table);
        Transaction tx1 = txManager.startShort(100);
        table.startTx(tx1);
        Assert.assertEquals("foobar-0", Bytes.toString(table.read("foo")));
        Assert.assertTrue(table.commitTx());
        txManager.canCommit(tx1, table.getTxChanges());
        txManager.commit(tx1);
        table.postTxCommit();
      } finally {
        cancellable.cancel();
      }
    } finally {
      dsFramework.deleteInstance(myTableInstance);
      feedManager.deleteFeed(FEED1);
    }
  }
 @Test(enabled = true, priority = 4)
 public void ThreemmSolventWeldWasteMuPVCProductPage() throws IOException, InterruptedException {
   File file = new File("C:\\Selenium\\jenkindemo\\src\\objectRepositry\\Products_PageObjects");
   FileInputStream input = new FileInputStream(file);
   Properties prop = new Properties();
   prop.load(input);
   dr.navigate().to(prop.getProperty("PlumbingWasteProductPage"));
   dr.findElement(By.xpath(prop.getProperty("SolventWeldWasteMuPVCProducts"))).click();
   WebElement Subproductname = dr.findElement(By.xpath(prop.getProperty("subproductname")));
   String Subproname = Subproductname.getText();
   System.out.println(
       "***********************************************************************************************");
   System.out.println("\t\tThe Sub Product Name is:" + Subproname);
   dr.findElement(By.xpath(prop.getProperty("32mmSolventWeldWasteMuPVCProducts"))).click();
   WebElement Subcatproductname = dr.findElement(By.xpath(prop.getProperty("subproductname")));
   String Subcatproname = Subcatproductname.getText();
   System.out.println(
       "***********************************************************************************************");
   System.out.println("\t\tThe Sub category Product Name is:" + Subcatproname);
   WebElement SubProduct = dr.findElement(By.xpath(prop.getProperty("subproduct")));
   List<WebElement> list = SubProduct.findElements(By.tagName("div"));
   int t = list.size();
   for (int i = 1; i <= t; i++) {
     String str1 = prop.getProperty("subproduct_part1");
     String str2 = prop.getProperty("subproduct_part2");
     dr.findElement(By.xpath(str1 + i + str2)).click();
     WebElement productname = dr.findElement(By.xpath(prop.getProperty("subcatproductname")));
     String finalcatproname = productname.getText();
     System.out.println(
         "***********************************************************************************************");
     System.out.println("\t\tThe Final Product Name is:" + finalcatproname);
     System.out.println(
         "***********************************************************************************************");
     WebElement FinalSubProduct = dr.findElement(By.xpath(prop.getProperty("FinalProduct")));
     List<WebElement> FinalSubproducts = FinalSubProduct.findElements(By.tagName("figure"));
     int Subtotal = FinalSubproducts.size();
     for (int n = 1; n <= Subtotal; n++) {
       String str5 = prop.getProperty("ProductImage_Part1");
       String str6 = prop.getProperty("ProductImage_Part2");
       String str8 = prop.getProperty("Finalproductname_part1a");
       String str13 = prop.getProperty("popupClose");
       int r = Subtotal + 1;
       JavascriptExecutor jse = (JavascriptExecutor) dr;
       jse.executeScript("scroll(0,-500);");
       TimeUnit.SECONDS.sleep(2);
       WebElement ProductName = dr.findElement(By.xpath(str5 + n + str8));
       String Name = ProductName.getText();
       String Proname = Name.replaceAll("[\r\n]+", " ");
       System.out.println("The Recently viewed product name is:" + Proname);
       dr.findElement(By.xpath(str5 + n + str6)).click();
       dr.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
       // ScreenCapture();
       TimeUnit.SECONDS.sleep(2);
       dr.findElement(By.xpath(str5 + r + str13)).click();
     }
     dr.navigate().to(prop.getProperty("32mmSolventWeldWasteMuPVCProductPage"));
   }
 }
  public boolean addCompoundToProjectDescription() throws InterruptedException {

    WebElement descToolBar = getProjDescToolBarElement();
    TimeUnit.SECONDS.sleep(1);
    WebElement compoundLoader = descToolBar.findElement(By.xpath("li[3]/a"));
    compoundLoader.click();
    TimeUnit.SECONDS.sleep(1);
    return drawCompound();
  }
Esempio n. 18
0
 /**
  * Cacheable can Asynchronous update.
  *
  * @throws Exception If something goes wrong
  */
 @Test
 public void asyncUpdateCacheSimpleCall() throws Exception {
   final CacheableTest.Foo foo = new CacheableTest.Foo(1L);
   final String first = foo.asyncGet().toString();
   MatcherAssert.assertThat(first, Matchers.equalTo(foo.asyncGet().toString()));
   TimeUnit.SECONDS.sleep(2);
   MatcherAssert.assertThat(first, Matchers.equalTo(foo.asyncGet().toString()));
   TimeUnit.SECONDS.sleep(2);
   MatcherAssert.assertThat(first, Matchers.not(Matchers.equalTo(foo.asyncGet().toString())));
 }
Esempio n. 19
0
 public static void main(String[] args) throws InterruptedException {
   TrackingExecutor executor = new TrackingExecutor(Executors.newFixedThreadPool(10));
   executor.execute(new SleepTask(2, TimeUnit.SECONDS));
   executor.execute(new SleepTask(2, TimeUnit.SECONDS));
   executor.execute(new SleepTask(2, TimeUnit.SECONDS));
   TimeUnit.SECONDS.sleep(1);
   executor.shutdownNow();
   TimeUnit.SECONDS.sleep(1);
   System.out.println(executor.getTaskCancelledSet().size());
 }
Esempio n. 20
0
    @Override
    public boolean load() throws Exception {
      Hosts.awaitDatabases();
      Locks.DISABLED.isLocked();
      Locks.PARTITIONED.isLocked();

      Groovyness.run("setup_dbpool.groovy");
      OrderedShutdown.registerShutdownHook(
          Empyrean.class,
          new Runnable() {

            @Override
            public void run() {
              try {
                for (String ctx : PersistenceContexts.list()) {
                  try {
                    DatabaseClusterMBean db = Databases.lookup(ctx, TimeUnit.SECONDS.toMillis(5));
                    for (String host : db.getinactiveDatabases()) {
                      Databases.disable(host);
                    }
                    for (String host : db.getactiveDatabases()) {
                      Databases.disable(host);
                    }
                  } catch (Exception ex) {
                    LOG.error(ex);
                  }
                }
              } catch (NoSuchElementException ex) {
                LOG.error(ex);
              }
            }
          });
      TimeUnit.SECONDS.sleep(INITIAL_DB_SYNC_RETRY_WAIT);
      if (!Hosts.isCoordinator() && Hosts.localHost().hasDatabase()) {
        while (!Databases.enable(Hosts.localHost())) {
          LOG.warn(
              LogUtil.subheader("Synchronization of the database failed: " + Hosts.localHost()));
          if (counter.decrementAndGet() == 0) {
            LOG.fatal("Restarting process to force re-synchronization.");
            System.exit(123);
          } else {
            LOG.warn(
                "Sleeping for " + INITIAL_DB_SYNC_RETRY_WAIT + " seconds before trying again.");
            TimeUnit.SECONDS.sleep(INITIAL_DB_SYNC_RETRY_WAIT);
          }
        }

        Locks.DISABLED.create();

        Hosts.UpdateEntry.INSTANCE.apply(Hosts.localHost());
        LOG.info(LogUtil.subheader("Database synchronization complete: " + Hosts.localHost()));
      }
      return true;
    }
    public static void main(String[] args) throws IOException, InterruptedException {
      ExecutorService exec = Executors.newCachedThreadPool();
      ServerSocket server = new ServerSocket(8080);
      InputStream socketInput = new Socket("localhost", 8080).getInputStream();

      Future<?> f = exec.submit(new IOBlockedTask(socketInput));
      TimeUnit.SECONDS.sleep(1);
      f.cancel(true);
      TimeUnit.SECONDS.sleep(1);
      System.out.println("Try closing input stream");
      socketInput.close();
      TimeUnit.SECONDS.sleep(5);
      System.exit(0);
    }
  public String addPaperFromPapersTab() throws InterruptedException {

    clickOnTab("tabs-key_papers-link");

    clickOnButton("add_paper");
    TimeUnit.SECONDS.sleep(3);

    String paperToAdd = addPaperFromSearchPub();
    TimeUnit.SECONDS.sleep(3);
    // back to project through breadscrumbs
    getWebDriver().findElement(By.xpath(".//*[@id='breadcrumbs']/ul/li[2]/span/a")).click();

    return checkPaperInList(paperToAdd);
  }
 private SingletonTest2() {
   try {
     System.out.println("SingletonTest2! constractor. start!");
     TimeUnit.SECONDS.sleep(2);
     if (instance3 == null) {
       instance3 = new SingletonTest2();
       System.out.println("instance3 created:" + instance3);
     }
     TimeUnit.SECONDS.sleep(2);
   } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Esempio n. 24
0
  public ColumnFamilyStore testSingleSSTableCompaction(String strategyClassName) throws Exception {
    Keyspace keyspace = Keyspace.open(KEYSPACE1);
    ColumnFamilyStore store = keyspace.getColumnFamilyStore("Standard1");
    store.clearUnsafe();
    store.metadata.gcGraceSeconds(1);
    store.setCompactionStrategyClass(strategyClassName);

    // disable compaction while flushing
    store.disableAutoCompaction();

    long timestamp = System.currentTimeMillis();
    for (int i = 0; i < 10; i++) {
      DecoratedKey key = Util.dk(Integer.toString(i));
      RowMutation rm = new RowMutation(KEYSPACE1, key.key);
      for (int j = 0; j < 10; j++)
        rm.add(
            "Standard1",
            ByteBufferUtil.bytes(Integer.toString(j)),
            ByteBufferUtil.EMPTY_BYTE_BUFFER,
            timestamp,
            j > 0
                ? 3
                : 0); // let first column never expire, since deleting all columns does not produce
                      // sstable
      rm.apply();
    }
    store.forceBlockingFlush();
    assertEquals(1, store.getSSTables().size());
    long originalSize = store.getSSTables().iterator().next().uncompressedLength();

    // wait enough to force single compaction
    TimeUnit.SECONDS.sleep(5);

    // enable compaction, submit background and wait for it to complete
    store.enableAutoCompaction();
    FBUtilities.waitOnFutures(CompactionManager.instance.submitBackground(store));
    while (CompactionManager.instance.getPendingTasks() > 0
        || CompactionManager.instance.getActiveCompactions() > 0) TimeUnit.SECONDS.sleep(1);

    // and sstable with ttl should be compacted
    assertEquals(1, store.getSSTables().size());
    long size = store.getSSTables().iterator().next().uncompressedLength();
    assertTrue("should be less than " + originalSize + ", but was " + size, size < originalSize);

    // make sure max timestamp of compacted sstables is recorded properly after compaction.
    assertMaxTimestamp(store, timestamp);

    return store;
  }
Esempio n. 25
0
  public static void main(String[] args) throws InterruptedException {

    {
      CountDownLatch startSignal = new CountDownLatch(1);
      CountDownLatch doneSignal = new CountDownLatch(N);

      for (int i = 0; i < N; ++i) // create and start threads
      new Thread(new Worker(startSignal, doneSignal)).start();

      TimeUnit.SECONDS.sleep(2);
      startSignal.countDown(); // let all threads proceed
      TimeUnit.SECONDS.sleep(2);
      doneSignal.await(); // wait for all to finish
    }
  }
  public boolean addReactionToProjectDescription() throws InterruptedException {

    WebElement descToolBar = getProjDescToolBarElement();
    TimeUnit.SECONDS.sleep(1);
    WebElement reactionLoader = descToolBar.findElement(By.xpath("./li[4]/a"));
    reactionLoader.click();

    TimeUnit.SECONDS.sleep(2);

    return openMarvinJSDialogAndImport(
        workingDir
            + LGConstants.ASSETS_FILES_DIRECTORY
            + LGConstants.REACTION_FILES_DIRECTORY
            + LGConstants.REACTION_FILE_TO_IMPORT);
  }
Esempio n. 27
0
  /**
   * Main method of the task. If the block of elements it has to process has 10 or more elements, it
   * divides the block in two and executes two subtasks to process those blocks. Else, sleeps the
   * task one second. Additionally, If the block of elements it has to process has the third
   * position, it throws an exception.
   */
  @Override
  protected Integer compute() {
    System.out.printf("Task: Start from %d to %d\n", start, end);
    if (end - start < 10) {
      if ((3 > start) && (3 < end)) {
        throw new RuntimeException(
            "This task throws an Exception: Task from  " + start + " to " + end);
      }

      try {
        TimeUnit.SECONDS.sleep(1);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

    } else {
      int mid = (end + start) / 2;
      Task task1 = new Task(array, start, mid);
      Task task2 = new Task(array, mid, end);
      invokeAll(task1, task2);
      System.out.printf("Task: Result form %d to %d: %d\n", start, mid, task1.join());
      System.out.printf("Task: Result form %d to %d: %d\n", mid, end, task2.join());
    }
    System.out.printf("Task: End form %d to %d\n", start, end);
    return new Integer(0);
  }
Esempio n. 28
0
  private static <T> T lookupMBean(
      final Map<String, String> props,
      final Class<T> type,
      final Predicate<T> tester,
      final long timeout) {
    long until = System.currentTimeMillis() + timeout;
    do
      try {
        final T bean = Mbeans.lookup(jdbcJmxDomain, props, type);
        tester.apply(bean);
        return bean;
      } catch (UndeclaredThrowableException e) {
        if (Exceptions.isCausedBy(e, InstanceNotFoundException.class)) {
          if (System.currentTimeMillis() < until) {
            try {
              TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e1) {
              Thread.interrupted();
              break;
            }
            LOG.debug("Waiting for MBean " + type.getSimpleName() + "/" + props);
            continue;
          }
          throw new NoSuchElementException(type.getSimpleName() + " " + props.toString());
        } else {
          throw Exceptions.toUndeclared(e);
        }
      }
    while (System.currentTimeMillis() < until);

    throw new NoSuchElementException(type.getSimpleName() + " " + props.toString());
  }
 @Override
 public String call() throws Exception {
   System.out.println("Start Printing");
   TimeUnit.SECONDS.sleep(new Random().nextInt(5));
   System.out.println("End Printing: " + requester + "_" + title);
   return requester + "_" + title;
 }
 public static void main(String[] args) throws InterruptedException {
   testThreadInterrupt(new SleepBlockedTask());
   testThreadInterrupt(new IOBlockedTask(System.in));
   testThreadInterrupt(new SynchronizedBlockedTask());
   TimeUnit.SECONDS.sleep(3);
   System.exit(0);
 }