/**
   * @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());
  }
  /** 現在のメイン画面を更新します */
  @Override
  public void run() {

    try {
      long nextUpdateTime = 0;
      long counter = 1;
      final ApplicationMain main = this.main;

      while (true) {
        final long current = counter++;

        Display.getDefault()
            .syncExec(
                new Runnable() {
                  @Override
                  public void run() {
                    // タイマー更新
                    TimerContext.get().update();

                    // 保有アイテム数を更新する
                    new UpdateItemCountTask(main).run();
                    // 保有艦娘数を更新する
                    new UpdateShipCountTask(main).run();
                    // 艦隊タブを更新する
                    new UpdateFleetTabTask(main).run();
                    // 遠征と入渠を更新する
                    new UpdateDeckNdockTask(main).run();

                    try {
                      // 更新日時が実装されているファイルたちはすぐに保存
                      ShipGroupConfig.store();
                      MasterData.store();
                      EnemyData.store();
                      ShipParameterRecord.store();
                      ScriptData.store();

                      if ((current % 10) == 0) {
                        // メニューから終了しなかった場合を考慮して定期的にウィンドウ位置を記憶
                        main.saveWindows();
                      }

                    } catch (IOException e) {
                      LOG.get().fatal("ファイル更新に失敗しました", e);
                    }
                  }
                });

        long currentTime = Calendar.getInstance().getTimeInMillis();
        // 次のアップデートは1秒後
        nextUpdateTime += TimeUnit.SECONDS.toMillis(1);
        if (nextUpdateTime < currentTime)
          nextUpdateTime = currentTime + TimeUnit.SECONDS.toMillis(1);

        Thread.sleep(nextUpdateTime - currentTime);
      }
    } catch (Exception e) {
      LOG.get().fatal("スレッドが異常終了しました", e);
      throw new RuntimeException(e);
    }
  }
  @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));
  }
  /*
   * (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();
    }
  }
  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;
  }
Beispiel #6
0
  @Test(groups = "slow")
  public void testInsertionTiming() {
    int keySpaceSize = 10000;
    int k = 100;
    int maxAdd = 100;
    TopK<Integer> topK = getInstance(keySpaceSize, k);

    LOG.info("Timing add() performance with keySpaceSize = %s, k = %s", keySpaceSize, k);

    Random random = new Random(0);
    long totalTime = 0;
    long count = 0;
    long begin = System.nanoTime();

    while (System.nanoTime() - begin < TEST_TIME_NANOS) {
      long start = System.nanoTime();

      topK.add(random.nextInt(keySpaceSize), random.nextInt(maxAdd));

      if (System.nanoTime() - begin > TimeUnit.SECONDS.toNanos(1)) {
        // discard the first second of measurements
        totalTime += System.nanoTime() - start;
        ++count;
      }
    }

    LOG.info(
        "Processed %s entries in %s ms. Insertion rate = %s entries/s",
        count,
        TimeUnit.NANOSECONDS.toMillis(totalTime),
        count / (totalTime * 1.0 / TimeUnit.SECONDS.toNanos(1)));
  }
 @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");
 }
  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;
  }
  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();
  }
Beispiel #10
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);
  }
Beispiel #12
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());
 }
Beispiel #13
0
  @Test
  public void testContextAwareTimer() {
    ContextAwareTimer jobTotalDuration = this.context.contextAwareTimer(TOTAL_DURATION);
    Assert.assertEquals(
        this.context
            .getTimers()
            .get(
                MetricRegistry.name(
                    this.context.metricNamePrefix(false), jobTotalDuration.getName())),
        jobTotalDuration);
    Assert.assertEquals(jobTotalDuration.getContext(), this.context);
    Assert.assertEquals(jobTotalDuration.getName(), TOTAL_DURATION);

    Assert.assertTrue(jobTotalDuration.getTags().isEmpty());
    jobTotalDuration.addTag(new Tag<String>(METRIC_GROUP_KEY, INPUT_RECORDS_GROUP));
    Assert.assertEquals(jobTotalDuration.getTags().size(), 1);
    Assert.assertEquals(jobTotalDuration.getTags().get(0).getKey(), METRIC_GROUP_KEY);
    Assert.assertEquals(jobTotalDuration.getTags().get(0).getValue(), INPUT_RECORDS_GROUP);
    Assert.assertEquals(
        jobTotalDuration.getFullyQualifiedName(false),
        MetricRegistry.name(INPUT_RECORDS_GROUP, TOTAL_DURATION));

    jobTotalDuration.update(50, TimeUnit.SECONDS);
    jobTotalDuration.update(100, TimeUnit.SECONDS);
    jobTotalDuration.update(150, TimeUnit.SECONDS);
    Assert.assertEquals(jobTotalDuration.getCount(), 3l);
    Assert.assertEquals(jobTotalDuration.getSnapshot().getMin(), TimeUnit.SECONDS.toNanos(50l));
    Assert.assertEquals(jobTotalDuration.getSnapshot().getMax(), TimeUnit.SECONDS.toNanos(150l));

    Assert.assertTrue(jobTotalDuration.time().stop() >= 0l);
  }
  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;
  }
  @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 contextDeadlineShouldNotOverrideSmallerMetadataTimeout() {
    long deadlineNanos = TimeUnit.SECONDS.toNanos(2);
    Context context =
        Context.current()
            .withDeadlineAfter(deadlineNanos, TimeUnit.NANOSECONDS, deadlineCancellationExecutor);
    context.attach();

    CallOptions callOpts = CallOptions.DEFAULT.withDeadlineAfter(1, TimeUnit.SECONDS);
    ClientCallImpl<Void, Void> call =
        new ClientCallImpl<Void, Void>(
            DESCRIPTOR,
            MoreExecutors.directExecutor(),
            callOpts,
            provider,
            deadlineCancellationExecutor);

    Metadata headers = new Metadata();

    call.start(callListener, headers);

    assertTrue(headers.containsKey(GrpcUtil.TIMEOUT_KEY));
    Long timeout = headers.get(GrpcUtil.TIMEOUT_KEY);
    assertNotNull(timeout);

    long callOptsNanos = TimeUnit.SECONDS.toNanos(1);
    long deltaNanos = TimeUnit.MILLISECONDS.toNanos(400);
    assertTimeoutBetween(timeout, callOptsNanos - deltaNanos, callOptsNanos);
  }
Beispiel #17
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"));
  }
  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);
  }
  @Test(timeout = 10000)
  public void testTimeoutsSetFromConnectionInfo() throws IOException, JMSException {
    final long CONNECT_TIMEOUT = TimeUnit.SECONDS.toMillis(4);
    final long CLOSE_TIMEOUT = TimeUnit.SECONDS.toMillis(5);
    final long SEND_TIMEOUT = TimeUnit.SECONDS.toMillis(6);
    final long REQUEST_TIMEOUT = TimeUnit.SECONDS.toMillis(7);

    provider = new FailoverProvider(uris, Collections.<String, String>emptyMap());
    provider.setProviderListener(
        new DefaultProviderListener() {

          @Override
          public void onConnectionEstablished(URI remoteURI) {}
        });

    provider.connect();
    provider.start();

    JmsConnectionInfo connectionInfo = createConnectionInfo();

    connectionInfo.setConnectTimeout(CONNECT_TIMEOUT);
    connectionInfo.setCloseTimeout(CLOSE_TIMEOUT);
    connectionInfo.setSendTimeout(SEND_TIMEOUT);
    connectionInfo.setRequestTimeout(REQUEST_TIMEOUT);

    ProviderFuture request = new ProviderFuture();
    provider.create(connectionInfo, request);
    request.sync();

    assertEquals(CONNECT_TIMEOUT, provider.getConnectTimeout());
    assertEquals(CLOSE_TIMEOUT, provider.getCloseTimeout());
    assertEquals(SEND_TIMEOUT, provider.getSendTimeout());
    assertEquals(REQUEST_TIMEOUT, provider.getRequestTimeout());
  }
  private Properties getDefaultProperties() {
    Properties defaultProps = new Properties();

    // testing params, DONT TOUCH !!!
    defaultProps.setProperty("openkad.keyfactory.keysize", "50");
    defaultProps.setProperty("openkad.keyfactory.hashalgo", "SHA-256");
    defaultProps.setProperty("openkad.bucket.kbuckets.maxsize", "16");
    defaultProps.setProperty("openkad.color.nrcolors", "19");
    defaultProps.setProperty("openkad.scheme.name", "openkad.udp");

    // performance params

    // handling incoming messages
    defaultProps.setProperty("openkad.executors.server.nrthreads", "8");
    defaultProps.setProperty("openkad.executors.server.max_pending", "512");
    // handling registered callback
    defaultProps.setProperty("openkad.executors.client.nrthreads", "1");
    defaultProps.setProperty("openkad.executors.client.max_pending", "20");
    // forwarding find node requests
    defaultProps.setProperty("openkad.executors.forward.nrthreads", "2");
    defaultProps.setProperty("openkad.executors.forward.max_pending", "2");
    // executing the long find node operations
    defaultProps.setProperty("openkad.executors.op.nrthreads", "1");
    defaultProps.setProperty("openkad.executors.op.max_pending", "2");
    // sending back pings
    defaultProps.setProperty("openkad.executors.ping.nrthreads", "1");
    defaultProps.setProperty("openkad.executors.ping.max_pending", "16");
    // cache settings
    defaultProps.setProperty("openkad.cache.validtime", TimeUnit.HOURS.toMillis(10) + "");
    defaultProps.setProperty("openkad.cache.size", "100");
    defaultProps.setProperty("openkad.cache.share", "1");
    // minimum time between successive pings
    defaultProps.setProperty("openkad.bucket.valid_timespan", TimeUnit.MINUTES.toMillis(1) + "");
    // network timeouts and concurrency level
    defaultProps.setProperty("openkad.net.concurrency", "1");
    defaultProps.setProperty("openkad.net.timeout", TimeUnit.SECONDS.toMillis(1000) + "");
    defaultProps.setProperty("openkad.net.forwarded.timeout", TimeUnit.SECONDS.toMillis(1200) + "");

    defaultProps.setProperty("openkad.color.candidates", "1");
    defaultProps.setProperty("openkad.color.slack.size", "1");
    defaultProps.setProperty("openkad.color.allcolors", "95");
    // interval between successive find node operations for refresh buckets
    defaultProps.setProperty("openkad.refresh.interval", TimeUnit.SECONDS.toMillis(30000) + "");

    // local configuration, please touch
    defaultProps.setProperty("openkad.net.udp.port", "-1");
    defaultProps.setProperty("openkad.local.key", "");
    defaultProps.setProperty("openkad.file.nodes.path", "nodes");

    // misc
    defaultProps.setProperty("openkad.seed", "0");

    // shani Skademia

    defaultProps.setProperty("skademlia.siblinglist.size", "8");
    defaultProps.setProperty("dht.storage.checkInterval", "" + TimeUnit.SECONDS.toMillis(30000));

    return defaultProps;
  }
Beispiel #21
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();
  }
 /**
  * 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())));
 }
 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());
 }
Beispiel #26
0
  /** Returns the source to satisfy {@code request} given this cached response. */
  public ResponseSource chooseResponseSource(long nowMillis, RequestHeaders request) {
    /*
     * If this response shouldn't have been stored, it should never be used
     * as a response source. This check should be redundant as long as the
     * persistence store is well-behaved and the rules are constant.
     */
    if (!isCacheable(request)) {
      return ResponseSource.NETWORK;
    }

    if (request.isNoCache() || request.hasConditions()) {
      return ResponseSource.NETWORK;
    }

    long ageMillis = computeAge(nowMillis);
    long freshMillis = computeFreshnessLifetime();

    if (request.getMaxAgeSeconds() != -1) {
      freshMillis = Math.min(freshMillis, TimeUnit.SECONDS.toMillis(request.getMaxAgeSeconds()));
    }

    long minFreshMillis = 0;
    if (request.getMinFreshSeconds() != -1) {
      minFreshMillis = TimeUnit.SECONDS.toMillis(request.getMinFreshSeconds());
    }

    long maxStaleMillis = 0;
    if (!mustRevalidate && request.getMaxStaleSeconds() != -1) {
      maxStaleMillis = TimeUnit.SECONDS.toMillis(request.getMaxStaleSeconds());
    }

    if (!noCache && ageMillis + minFreshMillis < freshMillis + maxStaleMillis) {
      if (ageMillis + minFreshMillis >= freshMillis) {
        headers.add("Warning", "110 HttpURLConnection \"Response is stale\"");
      }
      /*
       * not available in API 8
      if (ageMillis > TimeUnit.HOURS.toMillis(24) && isFreshnessLifetimeHeuristic()) {
      */
      if (ageMillis > 24L * 60L * 60L * 1000L && isFreshnessLifetimeHeuristic()) {
        headers.add("Warning", "113 HttpURLConnection \"Heuristic expiration\"");
      }
      return ResponseSource.CACHE;
    }

    if (etag != null) {
      request.setIfNoneMatch(etag);
    } else if (lastModified != null) {
      request.setIfModifiedSince(lastModified);
    } else if (servedDate != null) {
      request.setIfModifiedSince(servedDate);
    }

    return request.hasConditions() ? ResponseSource.CONDITIONAL_CACHE : ResponseSource.NETWORK;
  }
    @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;
    }
Beispiel #28
0
 public static CharSequence formatRoutingTime(
     Context context, int seconds, @DimenRes int unitsSize) {
   long minutes = TimeUnit.SECONDS.toMinutes(seconds) % 60;
   long hours = TimeUnit.SECONDS.toHours(seconds);
   String min = context.getString(R.string.minute);
   String hour = context.getString(R.string.hour);
   @DimenRes int textSize = R.dimen.text_size_routing_number;
   SpannableStringBuilder displayedH =
       Utils.formatUnitsText(context, textSize, unitsSize, String.valueOf(hours), hour);
   SpannableStringBuilder displayedM =
       Utils.formatUnitsText(context, textSize, unitsSize, String.valueOf(minutes), min);
   return hours == 0 ? displayedM : TextUtils.concat(displayedH + " ", displayedM);
 }
  /**
   * Tests update of session expiration in memcached (like {@link
   * #testExpirationOfSessionsInMemcachedIfBackupWasSkippedSimple()}) but for the scenario where
   * many readonly requests occur: in this case, we cannot just use <em>maxInactiveInterval -
   * secondsSinceLastBackup</em> (in {@link MemcachedSessionService#updateExpirationInMemcached}) to
   * determine if an expiration update is required, but we must use the last expiration time sent to
   * memcached.
   *
   * @throws Exception if something goes wrong with the http communication with tomcat
   */
  @Test(enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER)
  public void testExpirationOfSessionsInMemcachedIfBackupWasSkippedManyReadonlyRequests(
      final SessionAffinityMode stickyness) throws Exception {

    final SessionManager manager = _tomcat1.getManager();
    setStickyness(stickyness);

    // set to 1 sec above (in setup), default is 10 seconds
    final int delay = manager.getContainer().getBackgroundProcessorDelay();
    manager.setMaxInactiveInterval(delay * 4);

    final String sessionId1 = makeRequest(_httpClient, _portTomcat1, null);
    assertNotNull(sessionId1, "No session created.");
    assertWaitingWithProxy(Predicates.<MemcachedClientIF>notNull(), 200l, _memcached)
        .get(sessionId1);

    /* after 3 seconds make another request without changing the session, so that
     * it's not sent to memcached
     */
    Thread.sleep(TimeUnit.SECONDS.toMillis(delay * 3));
    assertEquals(
        makeRequest(_httpClient, _portTomcat1, sessionId1),
        sessionId1,
        "SessionId should be the same");
    assertNotNull(_memcached.get(sessionId1), "Session should still exist in memcached.");

    /* after another 3 seconds make another request without changing the session
     */
    Thread.sleep(TimeUnit.SECONDS.toMillis(delay * 3));
    assertEquals(
        makeRequest(_httpClient, _portTomcat1, sessionId1),
        sessionId1,
        "SessionId should be the same");
    assertNotNull(_memcached.get(sessionId1), "Session should still exist in memcached.");

    /* after another nearly 4 seconds (maxInactiveInterval) check that the session is still alive in memcached,
     * this would have been expired without an updated expiration
     */
    Thread.sleep(TimeUnit.SECONDS.toMillis(manager.getMaxInactiveInterval()) - 500);
    assertNotNull(_memcached.get(sessionId1), "Session should still exist in memcached.");

    /* after another second in sticky mode (more than 4 seconds since the last request), or an two times the
     * maxInactiveInterval in non-sticky mode (we must keep sessions in memcached with double expirationtime)
     * the session must be expired in memcached
     */
    Thread.sleep(TimeUnit.SECONDS.toMillis(delay) + 500);
    assertNotSame(
        makeRequest(_httpClient, _portTomcat1, sessionId1),
        sessionId1,
        "The sessionId should have changed due to expired sessin");
  }
  private DeploymentService.State getState() {
    if (deploymentLink != null) {
      URI serviceUri = UriUtils.buildUri(xenonHost, deploymentLink);

      Operation getOperation =
          Operation.createGet(serviceUri).setUri(serviceUri).setReferer(this.xenonHost.getUri());
      OperationLatch operationLatch = new OperationLatch(getOperation);
      xenonHost.sendRequest(getOperation);
      Operation completedOperation = null;
      try {
        completedOperation = operationLatch.awaitOperationCompletion(TimeUnit.SECONDS.toMicros(90));
      } catch (Throwable e) {
        logger.error("SysConfig get failed!! ", e);
        throw new RuntimeException(e);
      }

      return completedOperation.getBody(DeploymentService.State.class);
    } else {
      QueryTask.Query kindClause =
          new QueryTask.Query()
              .setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
              .setTermMatchValue(Utils.buildKind(DeploymentService.State.class));

      QueryTask.QuerySpecification querySpecification = new QueryTask.QuerySpecification();
      querySpecification.query = kindClause;

      Operation broadcastOp =
          xenonHost
              .getCloudStoreHelper()
              .createBroadcastPost(
                  ServiceUriPaths.CORE_LOCAL_QUERY_TASKS, ServiceUriPaths.DEFAULT_NODE_SELECTOR)
              .setBody(QueryTask.create(querySpecification).setDirect(true));
      OperationLatch operationLatch = new OperationLatch(broadcastOp);
      xenonHost.sendRequest(broadcastOp);
      Operation completedOperation = null;
      try {
        completedOperation = operationLatch.awaitOperationCompletion(TimeUnit.SECONDS.toMicros(90));
      } catch (Throwable e) {
        logger.error("SysConfig broadcastquery failed!! ", e);
        throw new RuntimeException(e);
      }

      Collection<String> documentLinks =
          QueryTaskUtils.getBroadcastQueryDocumentLinks(completedOperation);
      if (documentLinks.size() == 0) {
        return null;
      }
      this.deploymentLink = documentLinks.iterator().next();
      return getState();
    }
  }