Exemplo n.º 1
1
 private Set<Thread> collectCurrentThreads() {
   Thread[] activeThreadsT = new Thread[Thread.activeCount()];
   Thread.enumerate(activeThreadsT);
   Set<Thread> res = new HashSet<Thread>();
   for (Thread t : activeThreadsT) res.add(t);
   return res;
 }
 @Test
 public void removeListener() throws InterruptedException, IOException {
   HazelcastClient hClient = getHazelcastClient();
   final IMap<String, String> map = hClient.getMap("removeListener");
   final CountDownLatch entryAddLatch = new CountDownLatch(5);
   final CountDownLatch entryUpdatedLatch = new CountDownLatch(5);
   final CountDownLatch entryRemovedLatch = new CountDownLatch(5);
   CountDownLatchEntryListener<String, String> listener1 =
       new CountDownLatchEntryListener<String, String>(
           entryAddLatch, entryUpdatedLatch, entryRemovedLatch);
   CountDownLatchEntryListener<String, String> listener2 =
       new CountDownLatchEntryListener<String, String>(
           entryAddLatch, entryUpdatedLatch, entryRemovedLatch);
   map.addEntryListener(listener1, true);
   map.put("hello", "world");
   map.put("hello", "new world");
   map.remove("hello");
   Thread.sleep(100);
   assertEquals(4, entryAddLatch.getCount());
   assertEquals(4, entryRemovedLatch.getCount());
   assertEquals(4, entryUpdatedLatch.getCount());
   map.removeEntryListener(listener1);
   map.put("hello", "world");
   map.put("hello", "new world");
   map.remove("hello");
   Thread.sleep(100);
   assertEquals(4, entryAddLatch.getCount());
   assertEquals(4, entryRemovedLatch.getCount());
   assertEquals(4, entryUpdatedLatch.getCount());
 }
Exemplo n.º 3
0
  private static void testCallExitsOnClose(
      final QueueCall call, ClosableBlockingQueue<String> queue) throws Exception {

    final AtomicReference<Throwable> errorRef = new AtomicReference<>();

    Runnable runnable =
        new Runnable() {
          @Override
          public void run() {
            try {
              call.call();
            } catch (Throwable t) {
              errorRef.set(t);
            }
          }
        };

    Thread thread = new Thread(runnable);
    thread.start();
    Thread.sleep(100);
    queue.close();
    thread.join();

    @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
    Throwable cause = errorRef.get();
    assertTrue(cause instanceof IllegalStateException);
  }
Exemplo n.º 4
0
  @Test
  public void testChannelGroupReceive() throws Exception {
    final Channel<String> channel1 = newChannel();
    final Channel<String> channel2 = newChannel();
    final Channel<String> channel3 = newChannel();

    final ReceivePortGroup<String> group =
        new ReceivePortGroup<String>(channel1, channel2, channel3);

    Fiber fib =
        new Fiber(
                "fiber",
                fjPool,
                new SuspendableRunnable() {
                  @Override
                  public void run() throws SuspendExecution, InterruptedException {
                    String m1 = group.receive();
                    String m2 = channel2.receive();

                    assertThat(m1, equalTo("hello"));
                    assertThat(m2, equalTo("world!"));
                  }
                })
            .start();

    Thread.sleep(100);
    channel3.send("hello");
    Thread.sleep(100);
    if (policy != OverflowPolicy.BLOCK) {
      channel1.send("goodbye"); // TransferChannel will block here
      Thread.sleep(100);
    }
    channel2.send("world!");
    fib.join();
  }
Exemplo n.º 5
0
  @Test
  public void sendMessageFromThreadToThread() throws Exception {
    final Channel<String> ch = newChannel();

    Thread thread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                try {
                  Thread.sleep(100);

                  ch.send("a message");
                } catch (InterruptedException | SuspendExecution ex) {
                  throw new AssertionError(ex);
                }
              }
            });
    thread.start();

    String m = ch.receive();

    assertThat(m, equalTo("a message"));

    thread.join();
  }
  /**
   * Retransmission intervals (RC = Retransmission Counter): immediately send CON message, set RC =
   * 0 wait 2 - 3 sec then send retransmission, set RC = 1 wait 4 - 6 sec then send retransmission,
   * set RC = 2 wait 8 - 12 sec then send retransmission, set RC = 3 wait 16 - 24 sec then send
   * retransmission, set RC = 4 wait 32 - 48 sec then fail transmission
   *
   * @throws Exception
   */
  @Override
  public void createTestScenario() throws Exception {

    //             client                        testEndpoint     DESCRIPTION
    //                  |                             |
    //              (1) |----CON-GET----------------->|           Client sends confirmable request
    //                  |                             |
    //              (2) |----1st RETRANSMISSION------>|           (Client should send four
    // retransmissions)
    //                  |                             |
    //              (3) |----2nd RETRANSMISSION------>|
    //                  |                             |
    //              (4) |----3rd RETRANSMISSION------>|
    //                  |                             |
    //              (5) |----4th RETRANSMISSION------>|
    //                  |                             |
    //                  |                             |           internal timeout notification to
    // response processor

    // Send coapRequest
    InetSocketAddress remoteSocket = new InetSocketAddress("localhost", testEndpoint.getPort());
    timeRequestSent = System.currentTimeMillis();
    client.sendCoapRequest(coapRequest, remoteSocket, callback);

    // Wait for the message ID to retire (takes 247 seconds).
    Thread.sleep(48000);
    log.warn(
        "Now we have to wait for the message ID to time out (~200 seconds)... Time to get a coffee!");
    Thread.sleep(201000);
  }
Exemplo n.º 7
0
  private void echo(final SocketUDT connectorSocket, final ReadStrategy readStrategy) {

    final InputStream is = new NetInputStreamUDT(connectorSocket);
    final OutputStream os = new NetOutputStreamUDT(connectorSocket);

    final Runnable runner =
        new Runnable() {
          @Override
          public void run() {
            try {

              log.info("### ECHO: START");

              copy(is, os, TEST_BYTES.length, readStrategy);

              log.info("### ECHO: FINISH");

              // os.close();

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

    final Thread dt = new Thread(runner, "### server");
    dt.setDaemon(true);
    dt.start();
  }
  @BeforeClass
  public static void setUp() {
    duckGame = new DuckGame();

    LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
    config.width = 1280;
    config.height = 720;
    config.resizable = false;
    config.title = "SUPER DUCK INVADERS! - Team Mallard";
    new LwjglApplication(duckGame, config);

    while (duckGame.onGameScreen == false) {
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    testRound = new Round(duckGame, Assets.levelOneMap);
    try {
      Thread.sleep(200);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 9
0
 @Test
 public void testMultipleStartAndStop() throws IOException, InterruptedException {
   final HttpServer server1 = new HttpServer().port(8086);
   server1.start();
   assertEquals(404, client().newCall(request(8086).build()).execute().code());
   final HttpServer server2 = new HttpServer().port(8087);
   server2.start();
   assertEquals(404, client().newCall(request(8087).build()).execute().code());
   server1.shutdown();
   Thread.sleep(5000L);
   try {
     assertEquals(404, client().newCall(request(8086).build()).execute().code());
     fail("Server should have stopped");
   } catch (final ConnectException ignore) {
   } catch (final InterruptedIOException ignored) {
   }
   assertEquals(404, client().newCall(request(8087).build()).execute().code());
   server2.shutdown();
   Thread.sleep(5000L);
   try {
     assertEquals(404, client().newCall(request(8087).build()).execute().code());
     fail("Server should have stopped");
   } catch (final ConnectException ignore) {
   } catch (final InterruptedIOException ignored) {
   }
 }
Exemplo n.º 10
0
  // Test Case 6: Password Empty - Error
  private void profileSetUpPasswordEmpty() throws InterruptedException {

    profilePage1();
    driver.findElement(By.id("nickName")).click();
    driver.findElement(By.id("nickName")).clear();
    driver.findElement(By.id("nickName")).sendKeys("Neel");

    new Select(driver.findElement(By.id("DOBMonth"))).selectByVisibleText("January");
    driver.findElement(By.cssSelector("option[value=\"01\"]")).click();
    new Select(driver.findElement(By.id("DOBDay"))).selectByVisibleText("04");
    driver.findElement(By.cssSelector("#DOBDay > option[value=\"02\"]")).click();
    new Select(driver.findElement(By.id("DOBYear"))).selectByVisibleText("1994");
    driver.findElement(By.cssSelector("option[value=\"1994\"]")).click();

    driver.findElement(By.id("email")).click();
    driver.findElement(By.id("email")).clear();
    driver.findElement(By.id("email")).sendKeys("*****@*****.**");

    driver.findElement(By.id("emailConfirmation")).click();
    driver.findElement(By.id("emailConfirmation")).clear();
    driver.findElement(By.id("emailConfirmation")).sendKeys("*****@*****.**");

    driver.findElement(By.id("password")).click();
    driver.findElement(By.id("password")).clear();

    Thread.sleep(3000);

    driver.findElement(By.cssSelector("input.submitButton.green")).click();
    Thread.sleep(3000);
    System.out.println("ERROR: Password Missing");
  }
Exemplo n.º 11
0
  //  Delete CSR
  @Test
  public void Test5() throws Exception {
    driver.get(baseUrl + "/#/host/magehostmanager.magemojo.com/configuration/ssl");
    driver.findElement(By.xpath("//a[contains(text(),'www.Testing5.com')]")).click();
    assertEquals(
        "Download CSR www.Testing5.com", driver.findElement(By.xpath("//legend[4]")).getText());
    driver.findElement(By.xpath("(//button[@type='button'])[8]")).click();
    assertEquals(
        "Confirmation Window",
        driver.findElement(By.cssSelector("h3.modal-title.ng-binding")).getText());
    assertTrue(isElementPresent(By.xpath("//div[3]/button[2]")));
    driver.findElement(By.xpath("//div[3]/button")).click();

    for (int second = 0; ; second++) {
      if (second >= 60) fail("timeout");
      try {
        if ("Successfully deleted the CSR."
            .equals(driver.findElement(By.xpath("//div[@id='toast-container']/div")).getText()))
          break;
      } catch (Exception e) {
      }
      Thread.sleep(1000);
    }

    for (int second = 0; ; second++) {
      if (second >= 60) fail("timeout");
      try {
        if (!isElementPresent(By.xpath("//a[contains(text(),'www.Testing5.com')]"))) break;
      } catch (Exception e) {
      }
      Thread.sleep(1000);
    }
  }
  /*
   * @see DATAREDIS-415
   */
  @Test
  public void interruptAtStart() throws Exception {

    final Thread main = Thread.currentThread();

    // interrupt thread once Executor.execute is called
    doAnswer(
            new Answer<Object>() {

              @Override
              public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {

                main.interrupt();
                return null;
              }
            })
        .when(executorMock)
        .execute(any(Runnable.class));

    container.addMessageListener(adapter, new ChannelTopic("a"));
    container.start();

    // reset the interrupted flag to not destroy the teardown
    assertThat(Thread.interrupted(), is(true));

    assertThat(container.isRunning(), is(false));
  }
  /**
   * Initiator and target should successfully connect to the local SOCKS5 proxy.
   *
   * @throws Exception should not happen
   */
  @Test
  public void shouldSuccessfullyConnectThroughLocalSocks5Proxy() throws Exception {

    // start a local SOCKS5 proxy
    Socks5Proxy.setLocalSocks5ProxyPort(proxyPort);
    Socks5Proxy socks5Proxy = Socks5Proxy.getSocks5Proxy();
    socks5Proxy.start();

    // test data
    final byte[] data = new byte[] {1, 2, 3};

    // create digest
    final String digest = Socks5Utils.createDigest(sessionID, initiatorJID, targetJID);

    // allow connection of target with this digest
    socks5Proxy.addTransfer(digest);

    // build stream host information
    final StreamHost streamHost =
        new StreamHost(connection.getUser(), socks5Proxy.getLocalAddresses().get(0));
    streamHost.setPort(socks5Proxy.getPort());

    // target connects to local SOCKS5 proxy
    Thread targetThread =
        new Thread() {

          @Override
          public void run() {
            try {
              Socks5Client targetClient = new Socks5Client(streamHost, digest);
              Socket socket = targetClient.getSocket(10000);
              socket.getOutputStream().write(data);
            } catch (Exception e) {
              fail(e.getMessage());
            }
          }
        };
    targetThread.start();

    Thread.sleep(200);

    // initiator connects
    Socks5ClientForInitiator socks5Client =
        new Socks5ClientForInitiator(streamHost, digest, connection, sessionID, targetJID);

    Socket socket = socks5Client.getSocket(10000);

    // verify test data
    InputStream in = socket.getInputStream();
    for (int i = 0; i < data.length; i++) {
      assertEquals(data[i], in.read());
    }

    targetThread.join();

    protocol.verifyAll(); // assert no XMPP messages were sent

    socks5Proxy.removeTransfer(digest);
    socks5Proxy.stop();
  }
  // Call when not tracking state
  @Test
  public void testRunNotTracking() {
    sLogger.setWriter(new StringWriter());
    sLogger.start();
    assertTrue(sLogger.isRunning());
    ArrayList<StateGroup> grouplist = new ArrayList<>();
    grouplist.add(group);

    resetAll();
    expect(mockTracker.isTrackingState()).andReturn(false).anyTimes();
    expect(mockTracker.getIoSet()).andReturn(ioSet).anyTimes();
    expect(mockTracker.getStateList()).andReturn(grouplist).anyTimes();
    replayAll();

    Thread t =
        new Thread(
            new Runnable() {

              @Override
              public void run() {
                try {
                  Thread.sleep(2500);
                } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                }

                sLogger.stop();
              }
            });
    t.start();
    sLogger.run();
  }
  @Test
  public void testCoordinateListenerConnectionDiesReconnectAfterTimeout() throws Exception {
    final CountDownLatch connectedLatch1 = new CountDownLatch(2);
    final CountDownLatch connectedLatch2 = new CountDownLatch(6);
    TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1, connectedLatch2);
    assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS));
    assertEquals(
        CoordinateListener.Event.COORDINATE_OK, listener.events.get(listener.events.size() - 1));
    log.info("Killing connection");
    forwarder.terminate();

    log.info("Connection down.");

    Thread.sleep(9000);
    log.info("Recreating connection soon" + forwarderPort + "->" + zkport);
    Thread.sleep(1000);
    assertEquals(
        CoordinateListener.Event.NO_CONNECTION_TO_STORAGE,
        listener.events.get(listener.events.size() - 1));
    forwarder = new PortForwarder(forwarderPort, "127.0.0.1", zkport);
    assertTrue(connectedLatch2.await(20, TimeUnit.SECONDS));

    for (int c = 0; c < 100; c++) {
      if (CoordinateListener.Event.COORDINATE_OK
          == listener.events.get(listener.events.size() - 1)) {
        break;
      }
      Thread.sleep(300);
    }
    Thread.sleep(4500);
    assertEquals(
        CoordinateListener.Event.COORDINATE_OK, listener.events.get(listener.events.size() - 1));

    forwarder.terminate();
  }
Exemplo n.º 16
0
  @Test
  public void testRemovePackage() throws Exception {
    final org.drools.rule.Package pkg1 = new org.drools.rule.Package("org.droos.test");
    pkg1.setClassFieldAccessorCache(
        new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    pkg1.addGlobal("global1", Object.class);
    pkg1.addGlobal("global2", Object.class);

    final org.drools.rule.Package pkg2 = new org.drools.rule.Package("org.droos.test");
    pkg2.setClassFieldAccessorCache(
        new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    pkg2.addGlobal("global1", Object.class);
    pkg2.addGlobal("global3", Object.class);

    final org.drools.rule.Package pkg3 = new org.drools.rule.Package("org.droos.test2");
    pkg3.setClassFieldAccessorCache(
        new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    pkg3.addGlobal("global3", Object.class);
    pkg3.addGlobal("global4", Object.class);

    this.ruleBase.addPackage(pkg1);
    this.ruleBase.addPackage(pkg2);
    this.ruleBase.addPackage(pkg3);

    this.ruleBase.removePackage(pkg1.getName());
    // packages were partially merged when adding, so removal
    // shall left only package 3 behind
    assertLength(1, this.ruleBase.getPackages());
    assertLength(2, this.ruleBase.getGlobals().values());

    this.ruleBase.removePackage(pkg3.getName());
    assertLength(0, this.ruleBase.getPackages());
    assertLength(0, this.ruleBase.getGlobals().values());
  }
  /**
   * Tests the behavior of Zookeeper upon a restart. ZK should clean up old coordinates.
   *
   * @throws Exception
   */
  @Test
  public void testZookeeperRestarts() throws Exception {
    final CountDownLatch connectedLatch1 = new CountDownLatch(1);
    final CountDownLatch connectedLatch2 = new CountDownLatch(3);
    TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1, connectedLatch2);
    assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS));
    log.info("Killing zookeeper");
    forwarder.terminate();

    ezk.shutdown();
    ezk.del();
    ezk.init();
    Thread.sleep(2000);
    forwarder = new PortForwarder(forwarderPort, "127.0.0.1", zkport);

    int timeoutSecs = 30;
    while (--timeoutSecs > 0) {
      Thread.sleep(1000);
    }
    Coordinate c = Coordinate.parse("1.service.user.cell");
    cn.createCoordinate(c);

    Thread.sleep(9000);
    assertEquals(
        listener.events.get(listener.events.size() - 1), CoordinateListener.Event.COORDINATE_OK);
  }
Exemplo n.º 18
0
  @Test
  public void testAtomicUpdate() throws Exception {
    execute(
        "create local temporary table x (e1 string, e2 integer, primary key (e2))",
        new List[] {Arrays.asList(0)}); // $NON-NLS-1$
    execute(
        "insert into x (e2, e1) values (1, 'one')", new List[] {Arrays.asList(1)}); // $NON-NLS-1$
    execute(
        "insert into x (e2, e1) values (2, 'one')", new List[] {Arrays.asList(1)}); // $NON-NLS-1$
    try {
      execute("update x set e2 = 3", new List[] {Arrays.asList(1)}); // $NON-NLS-1$
    } catch (TeiidProcessingException e) {
      // should be a duplicate key
    }
    // should revert back to original
    execute("select count(*) from x", new List[] {Arrays.asList(2)}); // $NON-NLS-1$

    Thread t =
        new Thread() {
          public void run() {
            try {
              execute("select count(e1) from x", new List[] {Arrays.asList(2)});
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };
    t.start();
    t.join(2000);
    assertFalse(t.isAlive());
  }
 protected static void buildAndDeployMavenProject(String basedir) {
   // need to backup (and later restore) the current class loader, because the Maven/Plexus does
   // some classloader
   // magic which then results in CNFE in RestEasy client
   // run the Maven build which will create the kjar. The kjar is then either installed or deployed
   // to local and
   // remote repo
   logger.debug("Building and deploying Maven project from basedir '{}'.", basedir);
   ClassLoader classLoaderBak = Thread.currentThread().getContextClassLoader();
   MavenCli cli = new MavenCli();
   String[] mvnArgs;
   if (TestConfig.isLocalServer()) {
     // just install into local repository when running the local server. Deploying to remote repo
     // will fail
     // if the repo does not exist.
     mvnArgs = new String[] {"-B", "clean", "install"};
   } else {
     mvnArgs = new String[] {"-B", "clean", "deploy"};
   }
   int mvnRunResult = cli.doMain(mvnArgs, basedir, System.out, System.out);
   if (mvnRunResult != 0) {
     throw new RuntimeException(
         "Error while building Maven project from basedir "
             + basedir
             + ". Return code="
             + mvnRunResult);
   }
   Thread.currentThread().setContextClassLoader(classLoaderBak);
   logger.debug("Maven project successfully built and deployed!");
 }
  /**
   * Time a multi-threaded access to a cache.
   *
   * @return the timing stopwatch
   */
  private <V> StopWatch timeMultiThreaded(
      String id, final Map<Integer, V> map, ValueFactory<V> factory) throws InterruptedException {

    StopWatch stopWatch = new StopWatch(id);
    for (int i = 0; i < 500; i++) {
      map.put(i, factory.newValue(i));
    }
    Thread[] threads = new Thread[30];
    stopWatch.start("Running threads");
    for (int threadIndex = 0; threadIndex < threads.length; threadIndex++) {
      threads[threadIndex] =
          new Thread("Cache access thread " + threadIndex) {
            @Override
            public void run() {
              for (int j = 0; j < 1000; j++) {
                for (int i = 0; i < 1000; i++) {
                  map.get(i);
                }
              }
            }
          };
    }
    for (Thread thread : threads) {
      thread.start();
    }

    for (Thread thread : threads) {
      if (thread.isAlive()) {
        thread.join(2000);
      }
    }
    stopWatch.stop();
    return stopWatch;
  }
    @Override
    public void run(SourceContext<Tuple2<Long, IntType>> ctx) throws Exception {
      // we loop longer than we have elements, to permit delayed checkpoints
      // to still cause a failure
      while (running) {

        if (!failedBefore) {
          // delay a bit, if we have not failed before
          Thread.sleep(1);
          if (numSuccessfulCheckpoints >= 2 && numElementsEmitted >= failureAfterNumElements) {
            // cause a failure if we have not failed before and have reached
            // enough completed checkpoints and elements
            failedBefore = true;
            throw new Exception("Artificial Failure");
          }
        }

        if (numElementsEmitted < numElementsToEmit
            && (failedBefore || numElementsEmitted <= failureAfterNumElements)) {
          // the function failed before, or we are in the elements before the failure
          synchronized (ctx.getCheckpointLock()) {
            int next = numElementsEmitted++;
            for (long i = 0; i < numKeys; i++) {
              ctx.collectWithTimestamp(new Tuple2<Long, IntType>(i, new IntType(next)), next);
            }
            ctx.emitWatermark(new Watermark(next));
          }
        } else {

          // if our work is done, delay a bit to prevent busy waiting
          Thread.sleep(1);
        }
      }
    }
  @Test
  public void verifyServiceRemovals() throws Exception {
    final List<RegisteredService> list = new ArrayList<>(5);
    IntStream.range(1, 5)
        .forEach(
            i -> {
              final RegexRegisteredService r = new RegexRegisteredService();
              r.setServiceId("^https://.+");
              r.setName("testServiceType");
              r.setTheme("testtheme");
              r.setEvaluationOrder(1000);
              r.setId(i * 100);
              list.add(this.dao.save(r));
            });

    list.stream()
        .forEach(
            r2 -> {
              try {
                Thread.sleep(500);
                this.dao.delete(r2);
                Thread.sleep(2000);
              } catch (final InterruptedException e) {
                throw Throwables.propagate(e);
              }
              assertNull(this.dao.findServiceById(r2.getId()));
            });
  }
Exemplo n.º 23
0
  @Test
  public void testLifecycle() throws Exception {
    Timer timer = SettingsRefreshInterval.timer;
    RefreshInterval interval = SettingsRefreshInterval.CLASSPATH;
    interval.setMilliseconds(1);
    PS ps = new PS(interval);
    Settings s = new SettingsBuilder().add(ps).build();
    Reference<Settings> ref = new WeakReference<>(s);
    Thread.sleep(20);
    int cc = ps.callCount;
    assertNotSame("Refresh task not called", 0, cc);
    Thread.sleep(20);
    assertNotSame("Refresh task not being called continuously", cc, ps.callCount);
    s = null;
    for (int i = 0; i < 10; i++) {
      System.gc();
      if (ref.get() == null) {
        break;
      }
      Thread.sleep(200);
    }
    assertNull("Settings not garbage collected", ref.get());

    cc = ps.callCount;
    Thread.sleep(30);
    assertSame(
        "Settings garbage collected, but its internals are " + "still being refreshed",
        cc,
        ps.callCount);
  }
Exemplo n.º 24
0
  @Test
  public void multithreadedDateValueIndexFieldEncoding() {

    Thread[] threads = new Thread[10];
    for (int i = 0; i < threads.length; i++) {
      threads[i] =
          new Thread(
              new Runnable() {
                @Override
                public void run() {
                  dateValueIndexFieldEncoding();
                }
              });
    }
    for (Thread thread : threads) {
      thread.start();
    }
    for (Thread thread : threads) {
      try {
        thread.join();
      } catch (InterruptedException ie) {
        fail("Interrupted while waiting for test threads to finish.");
      }
    }
  }
Exemplo n.º 25
0
  @Ignore
  @Test
  public void whenReceiveNotCalledFromOwnerThenThrowException4() throws Exception {
    assumeTrue(Debug.isAssertionsEnabled());
    final Channel<String> ch = newChannel();

    Thread thread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                try {
                  ch.receive();
                } catch (InterruptedException ex) {
                  throw new AssertionError(ex);
                } catch (SuspendExecution e) {
                  throw new AssertionError(e);
                }
              }
            });
    thread.start();

    Thread.sleep(100);
    ch.send("a message");

    boolean thrown = false;
    try {
      ch.receive();
    } catch (Throwable e) {
      thrown = true;
    }
    assertTrue(thrown);

    thread.join();
  }
  @When("^I fill the signup form$")
  public void I_fill_the_signup_form() throws Throwable {
    // Add the details to create the account
    driver
        .findElement(By.id("ctl00_mainContentPlaceHolder_accountProfileForm_firstNameTextBox"))
        .sendKeys("Nikunj");
    driver
        .findElement(By.id("ctl00_mainContentPlaceHolder_accountProfileForm_emailAddressTextBox"))
        .sendKeys("*****@*****.**");
    driver
        .findElement(
            By.id("ctl00_mainContentPlaceHolder_accountProfileForm_emailAddressConfirmTextBox"))
        .sendKeys("*****@*****.**");
    driver
        .findElement(By.id("ctl00_mainContentPlaceHolder_accountProfileForm_passwordTextBox"))
        .sendKeys("Pass456Pass");
    driver
        .findElement(
            By.id("ctl00_mainContentPlaceHolder_accountProfileForm_passwordConfirmTextBox"))
        .sendKeys("Pass456Pass");
    driver
        .findElement(By.id("ctl00_mainContentPlaceHolder_accountProfileForm_zipCodeTextBox"))
        .sendKeys("61761");
    Thread.sleep(2000);
    driver.findElement(By.xpath("//option[@value='3']")).click();

    Thread.sleep(1000);
  }
Exemplo n.º 27
0
  @Test
  public void testGotoFinalReview() throws Exception {

    // Goto Final Review page
    driver.findElement(By.xpath("//a[contains(text(), 'Final Review')]")).click();
    try {
      assertEquals(
          "Final Review", driver.findElement(By.xpath("//*[@id='container']/h3")).getText());
    } catch (Error e) {
      screenShots.takeScreenShot("gotoFinalReview");
      verificationErrors.append(e.toString());
    }

    Thread.sleep(300);
    // Find where the warning is displayed and scroll it into view, then screenshot it.
    // We look for 'Scholarship and Sponsorship' since the warning is in the 'Qualifications' area
    // and the scrolling is causing a heading right where we scroll to and covers it.
    WebElement elem =
        driver.findElement(By.xpath("//h4[contains(text(), 'Scholarship and Sponsorship')]"));
    ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", elem);
    Thread.sleep(300);
    screenShots.takeScreenShot("FinalReviewWarnMsgNoQualifEntrd");

    // Go back to application
    driver.findElement(By.cssSelector("#link_to_application > span")).click();
  }
Exemplo n.º 28
0
  // Do some simple concurrent testing
  public void testConcurrentSimple() throws InterruptedException {
    final NonBlockingIdentityHashMap<String, String> nbhm =
        new NonBlockingIdentityHashMap<String, String>();
    final String[] keys = new String[20000];
    for (int i = 0; i < 20000; i++) keys[i] = "k" + i;

    // In 2 threads, add & remove even & odd elements concurrently
    Thread t1 =
        new Thread() {
          public void run() {
            work_helper(nbhm, "T1", 1, keys);
          }
        };
    t1.start();
    work_helper(nbhm, "T0", 0, keys);
    t1.join();

    // In the end, all members should be removed
    StringBuffer buf = new StringBuffer();
    buf.append("Should be emptyset but has these elements: {");
    boolean found = false;
    for (String x : nbhm.keySet()) {
      buf.append(" ").append(x);
      found = true;
    }
    if (found) System.out.println(buf + " }");
    assertThat("concurrent size=0", nbhm.size(), is(0));
    for (String x : nbhm.keySet()) {
      assertTrue("No elements so never get here", false);
    }
  }
Exemplo n.º 29
0
  @Test
  public void test2() {
    final Loop loop =
        new Loop(
            new LoopCallback() {

              @Override
              public int getMaxLoop() {
                return MAX_LOOP;
              }

              @Override
              public void setProgress(int progress) {
                // This won't work
                threadLog.get().add("Loop: " + 1);
              }
            });

    Thread loopThread =
        new Thread(
            new Runnable() {

              @Override
              public void run() {
                loop.doLoop();
              }
            });

    loopThread.start();

    // Only the local thread gets counted
    assertEquals(1, threadLog.get().size());
  }
  /** Test for issue #39 */
  @Test
  public void testIsMapKeyLocked() throws InterruptedException {
    HazelcastClient hClient = getHazelcastClient();
    final IMap map = hClient.getMap("testIsMapKeyLocked");
    assertFalse(map.isLocked("key"));
    map.lock("key");
    assertTrue(map.isLocked("key"));

    final CountDownLatch latch = new CountDownLatch(1);
    Thread thread =
        new Thread(
            new Runnable() {
              public void run() {
                assertTrue(map.isLocked("key"));
                try {
                  while (map.isLocked("key")) {
                    Thread.sleep(100);
                  }
                } catch (InterruptedException e) {
                  throw new RuntimeException(e);
                }
                latch.countDown();
              }
            });
    thread.start();
    Thread.sleep(100);
    map.unlock("key");
    assertTrue(latch.await(3, TimeUnit.SECONDS));
  }