@Test
  public void testResumeNext() {
    Subscription s = mock(Subscription.class);
    // Trigger failure on second element
    TestObservable f = new TestObservable(s, "one", "fail", "two", "three");
    Observable<String> w = Observable.create(f);
    Observable<String> resume = Observable.from("twoResume", "threeResume");
    Observable<String> observable = Observable.create(onErrorResumeNextViaObservable(w, resume));

    @SuppressWarnings("unchecked")
    Observer<String> observer = mock(Observer.class);
    observable.subscribe(observer);

    try {
      f.t.join();
    } catch (InterruptedException e) {
      fail(e.getMessage());
    }

    verify(observer, Mockito.never()).onError(any(Throwable.class));
    verify(observer, times(1)).onCompleted();
    verify(observer, times(1)).onNext("one");
    verify(observer, Mockito.never()).onNext("two");
    verify(observer, Mockito.never()).onNext("three");
    verify(observer, times(1)).onNext("twoResume");
    verify(observer, times(1)).onNext("threeResume");
  }
  @Test
  public void suspendSuspend() {
    System.out.println("suspend-suspend");
    final CountDownLatch barrier1 = new CountDownLatch(1);
    final CountDownLatch barrier2 = new CountDownLatch(2);

    SchedulerTask task =
        new SchedulerTask() {

          public void onSchedule(long timeStamp) {
            barrier1.countDown();
            barrier2.countDown();
          }
        };

    final ScheduledTask scheduled =
        Scheduler.sharedInstance().schedule(task, Quantum.seconds(2), false);
    stasks.add(scheduled);
    try {
      if (!barrier1.await(3, TimeUnit.SECONDS)) {
        fail();
      }
      scheduled.suspend();
      if (barrier2.await(3, TimeUnit.SECONDS)) {
        fail();
      }
      scheduled.suspend();
      if (barrier2.await(3, TimeUnit.SECONDS)) {
        fail();
      }
    } catch (InterruptedException e) {
      fail(e.getMessage());
    }
  }
  @Test
  public void dynamicRescheduleSuspended() {
    System.out.println("dynamicReschedule suspended");
    final CountDownLatch barrier1 = new CountDownLatch(1);
    final CountDownLatch barrier2 = new CountDownLatch(5);

    SchedulerTask task =
        new SchedulerTask() {

          public void onSchedule(long timeStamp) {
            System.out.println("dynamicReschedule; executing periodic task");
            barrier1.countDown();
            barrier2.countDown();
          }
        };

    final ScheduledTask scheduled =
        Scheduler.sharedInstance().schedule(task, Quantum.SUSPENDED, false);
    stasks.add(scheduled);
    try {
      if (barrier1.await(5, TimeUnit.SECONDS)) {
        fail();
      }
      scheduled.resume();
      if (barrier2.await(2, TimeUnit.SECONDS)) {
        fail();
      }
      scheduled.setInterval(Quantum.seconds(1));
      if (!barrier2.await(8, TimeUnit.SECONDS)) {
        fail();
      }
    } catch (InterruptedException e) {
      fail(e.getMessage());
    }
  }
  /**
   * Test of schedule method, immediate execution, blocking in the scheduled task, of class
   * Scheduler.
   */
  @Test
  public void scheduleImmediateBlocking() {
    System.out.println("schedule, immediate, blocking");
    final CountDownLatch barrier = new CountDownLatch(1);
    SchedulerTask task =
        new SchedulerTask() {

          public void onSchedule(long timeStamp) {
            try {
              barrier.countDown();
              Thread.sleep(10000000);
            } catch (InterruptedException e) {
              Thread.currentThread().interrupt();
            }
          }
        };
    Quantum interval = Quantum.seconds(2000);
    Scheduler instance = Scheduler.sharedInstance();
    ScheduledTask scheduled = instance.schedule(task, interval, true);
    stasks.add(scheduled);
    try {
      boolean executed = barrier.await(1000, TimeUnit.SECONDS);
      assertTrue(executed);
    } catch (InterruptedException e) {
      fail(e.getMessage());
    }
  }
Esempio n. 5
0
 public static void waitForElement(WebTester tester, String xpath) {
   int timeout = 7;
   for (int i = 0; i < timeout; i++) {
     try {
       tester.getElementByXPath(xpath);
       return;
     } catch (AssertionFailedError e) {
       // keep trying
     }
     try {
       Thread.sleep(200 + i * 500);
     } catch (InterruptedException e) {
       fail(e.getMessage());
     }
   }
   fail("Element not found (timeout: " + timeout + ") - " + xpath);
 }
 /**
  * Runs the simulation using the inputed EarthGridProperties
  *
  * @param simProp EarthGridProperties object defining the simulation to run.
  */
 private void runTest(EarthGridProperties simProp) {
   model.configure(simProp);
   model.start();
   while (true) {
     try {
       model.generate();
       pm.processMessageQueue();
     } catch (InterruptedException e) {
       assertEquals(true, e.getMessage().contains("Simulation Completed!"));
       break;
     } catch (Exception e) {
       e.printStackTrace();
       fail("ERROR: " + e.getMessage());
       break;
     }
   }
 }
  @Test
  public void testMapResumeAsyncNext() {
    Subscription sr = mock(Subscription.class);
    // Trigger multiple failures
    Observable<String> w = Observable.from("one", "fail", "two", "three", "fail");
    // Resume Observable is async
    TestObservable f = new TestObservable(sr, "twoResume", "threeResume");
    Observable<String> resume = Observable.create(f);

    // Introduce map function that fails intermittently (Map does not prevent this when the observer
    // is a
    //  rx.operator incl onErrorResumeNextViaObservable)
    w =
        w.map(
            new Func1<String, String>() {
              public String call(String s) {
                if ("fail".equals(s)) throw new RuntimeException("Forced Failure");
                System.out.println("BadMapper:" + s);
                return s;
              }
            });

    Observable<String> observable = Observable.create(onErrorResumeNextViaObservable(w, resume));

    @SuppressWarnings("unchecked")
    Observer<String> observer = mock(Observer.class);
    observable.subscribe(observer);

    try {
      f.t.join();
    } catch (InterruptedException e) {
      fail(e.getMessage());
    }

    verify(observer, Mockito.never()).onError(any(Throwable.class));
    verify(observer, times(1)).onCompleted();
    verify(observer, times(1)).onNext("one");
    verify(observer, Mockito.never()).onNext("two");
    verify(observer, Mockito.never()).onNext("three");
    verify(observer, times(1)).onNext("twoResume");
    verify(observer, times(1)).onNext("threeResume");
  }
  /** Test of unschedule method, of class Scheduler. */
  @Test
  public void unschedule() {
    System.out.println("unschedule");
    final AtomicBoolean executed = new AtomicBoolean(false);
    SchedulerTask task =
        new SchedulerTask() {

          public void onSchedule(long timeStamp) {
            executed.set(true);
          }
        };
    Scheduler instance = Scheduler.sharedInstance();
    ScheduledTask scheduled = instance.schedule(task, Quantum.seconds(3), false);
    instance.unschedule(scheduled);

    try {
      Thread.sleep(5000);
    } catch (InterruptedException e) {
      fail(e.getMessage());
    }
    assertFalse(executed.get());
  }
  /** Test of schedule method of class Scheduler. */
  @Test
  public void schedule() {
    System.out.println("schedule");
    final CountDownLatch barrier = new CountDownLatch(1);
    SchedulerTask task =
        new SchedulerTask() {

          public void onSchedule(long timeStamp) {
            barrier.countDown();
          }
        };
    Quantum interval = Quantum.seconds(5);
    Scheduler instance = Scheduler.sharedInstance();
    ScheduledTask scheduled = instance.schedule(task, interval, false);
    stasks.add(scheduled);
    try {
      boolean executed = barrier.await(8, TimeUnit.SECONDS);
      assertTrue(executed);
    } catch (InterruptedException e) {
      fail(e.getMessage());
    }
  }
Esempio n. 10
0
  /** Not compatible with our MVCC semantics. */
  private void __testMultiThreadedAccess() {

    Runnable runnable =
        new Runnable() {

          SailConnection sharedCon = con;

          public void run() {
            assertTrue(sharedCon != null);

            try {
              while (sharedCon.isActive()) {
                Thread.sleep(10);
              }
              sharedCon.begin();
              sharedCon.addStatement(painter, RDF.TYPE, RDFS.CLASS);
              sharedCon.commit();

              // wait a bit to allow other thread to add stuff as well.
              Thread.sleep(500L);
              CloseableIteration<? extends Statement, SailException> result =
                  sharedCon.getStatements(null, null, null, true);

              assertTrue(result.hasNext());
              int numberOfStatements = 0;
              while (result.hasNext()) {
                numberOfStatements++;
                Statement st = result.next();
                assertTrue(st.getSubject().equals(painter) || st.getSubject().equals(picasso));
                assertTrue(st.getPredicate().equals(RDF.TYPE));
                assertTrue(st.getObject().equals(RDFS.CLASS) || st.getObject().equals(painter));
              }
              assertTrue(
                  "we should have retrieved statements from both threads", numberOfStatements == 2);

            } catch (SailException e) {
              e.printStackTrace();
              fail(e.getMessage());
            } catch (InterruptedException e) {
              fail(e.getMessage());
            }

            // let this thread sleep so the other thread can invoke close()
            // first.
            try {
              Thread.sleep(1000L);

              // the connection should now be closed (by the other thread),
              // invoking any further operation should cause a
              // IllegalStateException
              sharedCon.getStatements(null, null, null, true);
              fail("should have caused an IllegalStateException");
            } catch (InterruptedException e) {
              fail(e.getMessage());
            } catch (SailException e) {
              e.printStackTrace();
              fail(e.getMessage());
            } catch (IllegalStateException e) {
              // do nothing, this is the expected behaviour
            }
          }
        }; // end anonymous class declaration

    // execute the other thread
    Thread newThread = new Thread(runnable, "B (parallel)");
    newThread.start();

    try {
      while (con.isActive()) {
        Thread.sleep(10);
      }
      con.begin();
      con.addStatement(picasso, RDF.TYPE, painter);
      con.commit();
      // let this thread sleep to enable other thread to finish its business.
      Thread.sleep(1000L);
      con.close();
    } catch (SailException e) {
      e.printStackTrace();
      fail(e.getMessage());
    } catch (InterruptedException e) {
      fail(e.getMessage());
    }
  }
Esempio n. 11
0
  @Test
  public void test() {
    node2.registerMessageObserver(
        new ConcreteObserver<Message>() {
          @Override
          public void notifyObserver(Message e) {
            if (e.has("content") && e.getString("content").equals("message1")) {
              recievedMessage1 = true;
            }
            if (e.has("content") && e.getString("content").equals("message3")) {
              fail("Recieved message while being in stopped state.");
            }
          }
        });
    node3.registerMessageObserver(
        new ConcreteObserver<Message>() {
          @Override
          public void notifyObserver(Message e) {
            if (e.has("content") && e.getString("content").equals("message2")) {
              recievedMessage2 = true;
            }
            if (e.has("content") && e.getString("content").equals("message4")) {
              recievedMessage4 = true;
            }
            if (e.has("content") && e.getString("content").equals("message5")) {
              fail("Recieved message from stopped node");
            }
          }
        });

    Message message = new Message();
    message.setDestinationAddress(node2.getAddress());
    message.setKey("content", "message1");
    node1.send(message);
    message = new Message();
    message.setDestinationAddress(node3.getAddress());
    message.setKey("content", "message2");
    node2.send(message);
    node2.stop();
    message = new Message();
    message.setDestinationAddress(node2.getAddress());
    message.setKey("content", "message3");
    node1.send(message);
    message = new Message();
    message.setDestinationAddress(node3.getAddress());
    message.setKey("content", "message4");
    node1.send(message);
    message = new Message();
    message.setDestinationAddress(node3.getAddress());
    message.setKey("content", "message5");
    assertFalse(node2.send(message));
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e1) {
      fail(e1.getMessage());
    }
    assertTrue(recievedMessage1);
    assertTrue(recievedMessage2);
    assertTrue(recievedMessage4);
    assertTrue(node2.getConnections().size() == 0);
    for (Entry<Address, Connection> e : node1.getConnections().entrySet()) {
      assertEquals(e.getKey(), e.getValue().getAddress());
      assertFalse(e.getKey().equals(node2.getAddress()));
    }
    for (Entry<Address, Connection> e : node3.getConnections().entrySet()) {
      assertEquals(e.getKey(), e.getValue().getAddress());
      assertFalse(e.getKey().equals(node3.getAddress()));
    }
  }
Esempio n. 12
0
  @Test
  public void testEvictionSpeedTestPerPartition() {
    final int k = 2;
    final int size = 100;
    final CountDownLatch latch = new CountDownLatch(k);
    final String mapName = "testEvictionSpeedTestPerPartition";
    Config cfg = new Config();
    final MapConfig mc = cfg.getMapConfig(mapName);
    mc.setEvictionPolicy(MapConfig.EvictionPolicy.LRU);
    mc.setEvictionPercentage(25);
    final MaxSizeConfig msc = new MaxSizeConfig();
    msc.setMaxSizePolicy(MaxSizeConfig.MaxSizePolicy.PER_PARTITION);
    msc.setSize(size);
    mc.setMaxSizeConfig(msc);

    TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k);
    final HazelcastInstance[] instances = factory.newInstances(cfg);
    final int pnum = instances[0].getPartitionService().getPartitions().size();
    final AtomicInteger failCount = new AtomicInteger(0);

    new Thread() {
      final IMap map = instances[0].getMap(mapName);

      public void run() {
        try {
          Thread.sleep(1000);
          while (latch.getCount() != 0) {
            try {
              int msize = map.size();
              if (msize > (size * pnum * 1.2)) {
                failCount.incrementAndGet();
              }
              Thread.sleep(1000);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }.start();

    for (int i = 0; i < k; i++) {
      final IMap map = instances[i].getMap(mapName);
      new Thread() {
        public void run() {
          for (int j = 0; j < 100000; j++) {
            map.put(k + "-" + j, j);
          }
          latch.countDown();
        }
      }.start();
    }

    try {
      Assert.assertEquals(latch.await(10, TimeUnit.MINUTES), true);
      Assert.assertEquals(0, failCount.get());
    } catch (InterruptedException e) {
      e.printStackTrace();
      Assert.fail(e.getMessage());
    }
  }
Esempio n. 13
0
  // current eviction check period is 1 second.
  // about 30.000 records can be put in one second
  // so the size should be adapted
  @Test
  public void testEvictionSpeedTest() {
    final int k = 3;
    final int size = 10000;
    final CountDownLatch latch = new CountDownLatch(k);
    final String mapName = "testEvictionSpeedTest";
    Config cfg = new Config();
    final MapConfig mc = cfg.getMapConfig(mapName);
    mc.setEvictionPolicy(MapConfig.EvictionPolicy.LRU);
    mc.setEvictionPercentage(25);
    final MaxSizeConfig msc = new MaxSizeConfig();
    msc.setMaxSizePolicy(MaxSizeConfig.MaxSizePolicy.PER_NODE);
    msc.setSize(size);
    mc.setMaxSizeConfig(msc);

    TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(k);
    final HazelcastInstance[] instances = factory.newInstances(cfg);
    final AtomicBoolean success = new AtomicBoolean(true);

    new Thread() {
      final IMap map = instances[0].getMap(mapName);

      public void run() {
        try {
          Thread.sleep(1000);
          while (latch.getCount() != 0) {
            try {
              int msize = map.size();
              if (msize > (size * k + size * k * 10 / 100)) {
                success.set(false);
                break;
              }
              Thread.sleep(1000);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }.start();

    for (int i = 0; i < k; i++) {
      final IMap map = instances[i].getMap(mapName);
      new Thread() {
        public void run() {
          for (int j = 0; j < size; j++) {
            map.put(k + "-" + j, j);
          }
          latch.countDown();
        }
      }.start();
    }

    try {
      Assert.assertTrue(latch.await(10, TimeUnit.MINUTES));
      Assert.assertTrue(success.get());
    } catch (InterruptedException e) {
      e.printStackTrace();
      Assert.fail(e.getMessage());
    }
  }