/* * Launches against the agent& main */ public void testAgentAndMain() throws Exception { Project project = workspace.getProject("p1"); Run bndrun = new Run(workspace, project.getBase(), project.getFile("one.bndrun")); bndrun.setProperty("-runpath", "biz.aQute.remote.launcher"); bndrun.setProperty("-runbundles", "bsn-1,bsn-2"); bndrun.setProperty("-runremote", "agent,main;agent=1090"); final RemoteProjectLauncherPlugin pl = (RemoteProjectLauncherPlugin) bndrun.getProjectLauncher(); pl.prepare(); List<? extends RunSession> sessions = pl.getRunSessions(); assertEquals(2, sessions.size()); RunSession agent = sessions.get(0); RunSession main = sessions.get(1); CountDownLatch agentLatch = launch(agent); CountDownLatch mainLatch = launch(main); agent.waitTillStarted(1000); main.waitTillStarted(1000); Thread.sleep(500); agent.cancel(); main.cancel(); agentLatch.await(); mainLatch.await(); assertEquals(-3, agent.getExitCode()); assertEquals(-3, main.getExitCode()); bndrun.close(); }
@Ignore("Non-positive requests are relayed to the plugin and is a no-op otherwise") @Test public void testNegativeRequestThrowsIllegalArgumentException() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> exception = new AtomicReference<>(); Observable.just(1, 2, 3, 4) .subscribe( new Observer<Integer>() { @Override public void onStart() { request(1); } @Override public void onComplete() {} @Override public void onError(Throwable e) { exception.set(e); latch.countDown(); } @Override public void onNext(Integer t) { request(-1); request(1); } }); Assert.assertTrue(latch.await(10, TimeUnit.SECONDS)); Assert.assertTrue(exception.get() instanceof IllegalArgumentException); }
/** * https://github.com/ReactiveX/RxJava/issues/198 * * <p>Rx Design Guidelines 5.2 * * <p>"when calling the Subscribe method that only has an onNext argument, the OnError behavior * will be to rethrow the exception on the thread that the message comes out from the Observable. * The OnCompleted behavior in this case is to do nothing." * * @throws InterruptedException */ @Test @Ignore("Subscribers can't throw") public void testErrorThrownWithoutErrorHandlerAsynchronous() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> exception = new AtomicReference<>(); Observable.create( observer -> { new Thread( () -> { try { observer.onError(new Error("failure")); } catch (Throwable e) { // without an onError handler it has to just throw on whatever thread // invokes it exception.set(e); } latch.countDown(); }) .start(); }) .subscribe(); // wait for exception latch.await(3000, TimeUnit.MILLISECONDS); assertNotNull(exception.get()); assertEquals("failure", exception.get().getMessage()); }
@Test public void testPublishLast() throws InterruptedException { final AtomicInteger count = new AtomicInteger(); ConnectableObservable<String> connectable = Observable.<String>create( observer -> { observer.onSubscribe(EmptySubscription.INSTANCE); count.incrementAndGet(); new Thread( () -> { observer.onNext("first"); observer.onNext("last"); observer.onComplete(); }) .start(); }) .takeLast(1) .publish(); // subscribe once final CountDownLatch latch = new CountDownLatch(1); connectable.subscribe( value -> { assertEquals("last", value); latch.countDown(); }); // subscribe twice connectable.subscribe(); Disposable subscription = connectable.connect(); assertTrue(latch.await(1000, TimeUnit.MILLISECONDS)); assertEquals(1, count.get()); subscription.dispose(); }
/** {@inheritDoc} */ @Override public void onUpdate(int cnt) { assert cnt >= 0; this.cnt = cnt; while (internalLatch != null && internalLatch.getCount() > cnt) internalLatch.countDown(); }
/* * Launches against the agent */ public void testSimpleLauncher() throws Exception { Project project = workspace.getProject("p1"); Run bndrun = new Run(workspace, project.getBase(), project.getFile("one.bndrun")); bndrun.setProperty("-runpath", "biz.aQute.remote.launcher"); bndrun.setProperty("-runbundles", "bsn-1,bsn-2"); bndrun.setProperty("-runremote", "test"); final RemoteProjectLauncherPlugin pl = (RemoteProjectLauncherPlugin) bndrun.getProjectLauncher(); pl.prepare(); final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger exitCode = new AtomicInteger(-1); List<? extends RunSession> sessions = pl.getRunSessions(); assertEquals(1, sessions.size()); final RunSession session = sessions.get(0); Thread t = new Thread("test-launch") { public void run() { try { exitCode.set(session.launch()); } catch (Exception e) { e.printStackTrace(); } finally { latch.countDown(); } } }; t.start(); Thread.sleep(500); for (Bundle b : context.getBundles()) { System.out.println(b.getLocation()); } assertEquals(4, context.getBundles().length); String p1 = t1.getAbsolutePath(); System.out.println(p1); assertNotNull(context.getBundle(p1)); assertNotNull(context.getBundle(t2.getAbsolutePath())); pl.cancel(); latch.await(); assertEquals(-3, exitCode.get()); bndrun.close(); }
@Test public void testReplay() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(); ConnectableObservable<String> o = Observable.<String>create( observer -> { observer.onSubscribe(EmptySubscription.INSTANCE); new Thread( new Runnable() { @Override public void run() { counter.incrementAndGet(); observer.onNext("one"); observer.onComplete(); } }) .start(); }) .replay(); // we connect immediately and it will emit the value Disposable s = o.connect(); try { // we then expect the following 2 subscriptions to get that same value final CountDownLatch latch = new CountDownLatch(2); // subscribe once o.subscribe( v -> { assertEquals("one", v); latch.countDown(); }); // subscribe again o.subscribe( v -> { assertEquals("one", v); latch.countDown(); }); if (!latch.await(1000, TimeUnit.MILLISECONDS)) { fail("subscriptions did not receive values"); } assertEquals(1, counter.get()); } finally { s.dispose(); } }
/** @throws Exception If failed. */ public void testTopologyListener() throws Exception { final Collection<UUID> added = new ArrayList<>(1); final Collection<UUID> rmvd = new ArrayList<>(1); final CountDownLatch addedLatch = new CountDownLatch(1); final CountDownLatch rmvLatch = new CountDownLatch(1); assertEquals(NODES_CNT, client.compute().refreshTopology(false, false).size()); GridClientTopologyListener lsnr = new GridClientTopologyListener() { @Override public void onNodeAdded(GridClientNode node) { added.add(node.nodeId()); addedLatch.countDown(); } @Override public void onNodeRemoved(GridClientNode node) { rmvd.add(node.nodeId()); rmvLatch.countDown(); } }; client.addTopologyListener(lsnr); try { Grid g = startGrid(NODES_CNT + 1); UUID id = g.localNode().id(); assertTrue(addedLatch.await(2 * TOP_REFRESH_FREQ, MILLISECONDS)); assertEquals(1, added.size()); assertEquals(id, F.first(added)); stopGrid(NODES_CNT + 1); assertTrue(rmvLatch.await(2 * TOP_REFRESH_FREQ, MILLISECONDS)); assertEquals(1, rmvd.size()); assertEquals(id, F.first(rmvd)); } finally { client.removeTopologyListener(lsnr); stopGrid(NODES_CNT + 1); } }
/** @throws GridException If operation failed. */ private void initializeLatch() throws GridException { if (initGuard.compareAndSet(false, true)) { try { internalLatch = CU.outTx( new Callable<CountDownLatch>() { @Override public CountDownLatch call() throws Exception { GridCacheTx tx = CU.txStartInternal(ctx, latchView, PESSIMISTIC, REPEATABLE_READ); try { GridCacheCountDownLatchValue val = latchView.get(key); if (val == null) { if (log.isDebugEnabled()) log.debug("Failed to find count down latch with given name: " + name); assert cnt == 0; return new CountDownLatch(cnt); } tx.commit(); return new CountDownLatch(val.get()); } finally { tx.end(); } } }, ctx); if (log.isDebugEnabled()) log.debug("Initialized internal latch: " + internalLatch); } finally { initLatch.countDown(); } } else { try { initLatch.await(); } catch (InterruptedException ignored) { throw new GridException("Thread has been interrupted."); } if (internalLatch == null) throw new GridException("Internal latch has not been properly initialized."); } }
/** * Event callback. * * @param exchId Exchange ID. * @param discoEvt Discovery event. */ public void onEvent(GridDhtPartitionExchangeId exchId, DiscoveryEvent discoEvt) { assert exchId.equals(this.exchId); this.discoEvt = discoEvt; evtLatch.countDown(); }
public void run() { done.countDown(); remaining.incrementAndGet(); int n; while (!Thread.interrupted() && (n = remaining.get()) > 0 && done.getCount() > 0) { if (remaining.compareAndSet(n, n - 1)) { try { pool.execute(this); } catch (RuntimeException ex) { System.out.print("*"); while (done.getCount() > 0) done.countDown(); return; } } } }
/** {@inheritDoc} */ @Override public void await() throws GridException { initializeLatch(); try { internalLatch.await(); } catch (InterruptedException e) { throw new GridInterruptedException(e); } }
/** {@inheritDoc} */ @Override public boolean await(long timeout, TimeUnit unit) throws GridException { initializeLatch(); try { return internalLatch.await(timeout, unit); } catch (InterruptedException e) { throw new GridInterruptedException(e); } }
/** * The error from the user provided Observer is not handled by the subscribe method try/catch. * * <p>It is handled by the AtomicObserver that wraps the provided Observer. * * <p>Result: Passes (if AtomicObserver functionality exists) */ @Test public void testCustomObservableWithErrorInObserverAsynchronous() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger count = new AtomicInteger(); final AtomicReference<Throwable> error = new AtomicReference<>(); // FIXME custom built??? Observable.just("1", "2", "three", "4") .subscribeOn(Schedulers.newThread()) .safeSubscribe( new Observer<String>() { @Override public void onComplete() { System.out.println("completed"); latch.countDown(); } @Override public void onError(Throwable e) { error.set(e); System.out.println("error"); e.printStackTrace(); latch.countDown(); } @Override public void onNext(String v) { int num = Integer.parseInt(v); System.out.println(num); // doSomething(num); count.incrementAndGet(); } }); // wait for async sequence to complete latch.await(); assertEquals(2, count.get()); assertNotNull(error.get()); if (!(error.get() instanceof NumberFormatException)) { fail("It should be a NumberFormatException"); } }
static void oneRun(BlockingQueue<Runnable> q, int nThreads, int iters, boolean print) throws Exception { ThreadPoolExecutor pool = new ThreadPoolExecutor(nThreads + 1, Integer.MAX_VALUE, 1L, TimeUnit.SECONDS, q); CountDownLatch done = new CountDownLatch(iters); remaining.set(nThreads - 1); pool.prestartAllCoreThreads(); Task t = new Task(pool, done); long start = System.nanoTime(); pool.execute(t); done.await(); long time = System.nanoTime() - start; if (print) System.out.println("\t: " + LoopHelpers.rightJustify(time / iters) + " ns per task"); q.clear(); Thread.sleep(100); pool.shutdown(); Thread.sleep(100); pool.shutdownNow(); }
@Test public void testCacheWithCapacity() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(); Observable<String> o = Observable.<String>create( observer -> { observer.onSubscribe(EmptySubscription.INSTANCE); new Thread( () -> { counter.incrementAndGet(); observer.onNext("one"); observer.onComplete(); }) .start(); }) .cache(1); // we then expect the following 2 subscriptions to get that same value final CountDownLatch latch = new CountDownLatch(2); // subscribe once o.subscribe( v -> { assertEquals("one", v); latch.countDown(); }); // subscribe again o.subscribe( v -> { assertEquals("one", v); latch.countDown(); }); if (!latch.await(1000, TimeUnit.MILLISECONDS)) { fail("subscriptions did not receive values"); } assertEquals(1, counter.get()); }
/** {@inheritDoc} */ @Override public String toString() { ClusterNode oldestNode = this.oldestNode.get(); return S.toString( GridDhtPartitionsExchangeFuture.class, this, "oldest", oldestNode == null ? "null" : oldestNode.id(), "oldestOrder", oldestNode == null ? "null" : oldestNode.order(), "evtLatch", evtLatch == null ? "null" : evtLatch.getCount(), "remaining", remaining(), "super", super.toString()); }
/** * Initializes store. * * @throws GridException If failed to initialize. */ private void init() throws GridException { if (initGuard.compareAndSet(false, true)) { if (log.isDebugEnabled()) log.debug("Initializing cache store."); try { if (sesFactory != null) // Session factory has been provided - nothing to do. return; if (!F.isEmpty(hibernateCfgPath)) { try { URL url = new URL(hibernateCfgPath); sesFactory = new Configuration().configure(url).buildSessionFactory(); if (log.isDebugEnabled()) log.debug("Configured session factory using URL: " + url); // Session factory has been successfully initialized. return; } catch (MalformedURLException e) { if (log.isDebugEnabled()) log.debug("Caught malformed URL exception: " + e.getMessage()); } // Provided path is not a valid URL. File? File cfgFile = new File(hibernateCfgPath); if (cfgFile.exists()) { sesFactory = new Configuration().configure(cfgFile).buildSessionFactory(); if (log.isDebugEnabled()) log.debug("Configured session factory using file: " + hibernateCfgPath); // Session factory has been successfully initialized. return; } // Provided path is not a file. Classpath resource? sesFactory = new Configuration().configure(hibernateCfgPath).buildSessionFactory(); if (log.isDebugEnabled()) log.debug("Configured session factory using classpath resource: " + hibernateCfgPath); } else { if (hibernateProps == null) { U.warn( log, "No Hibernate configuration has been provided for store (will use default)."); hibernateProps = new Properties(); hibernateProps.setProperty("hibernate.connection.url", DFLT_CONN_URL); hibernateProps.setProperty("hibernate.show_sql", DFLT_SHOW_SQL); hibernateProps.setProperty("hibernate.hbm2ddl.auto", DFLT_HBM2DDL_AUTO); } Configuration cfg = new Configuration(); cfg.setProperties(hibernateProps); assert resourceAvailable(MAPPING_RESOURCE); cfg.addResource(MAPPING_RESOURCE); sesFactory = cfg.buildSessionFactory(); if (log.isDebugEnabled()) log.debug("Configured session factory using properties: " + hibernateProps); } } catch (HibernateException e) { throw new GridException("Failed to initialize store.", e); } finally { initLatch.countDown(); } } else if (initLatch.getCount() > 0) U.await(initLatch); if (sesFactory == null) throw new GridException("Cache store was not properly initialized."); }
@Test public void testUserSubscriberUsingRequestAsync() throws InterruptedException { AtomicInteger c = new AtomicInteger(); final AtomicInteger totalReceived = new AtomicInteger(); final AtomicInteger received = new AtomicInteger(); final AtomicInteger batches = new AtomicInteger(); final CountDownLatch latch = new CountDownLatch(1); incrementingIntegers(c) .subscribeOn(Schedulers.newThread()) .subscribe( new Subscriber<Integer>() { @Override public void onStart() { request(100); } @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable e) { latch.countDown(); } @Override public void onNext(Integer t) { int total = totalReceived.incrementAndGet(); received.incrementAndGet(); boolean done = false; if (total >= 2000) { done = true; unsubscribe(); } if (received.get() == 100) { batches.incrementAndGet(); received.set(0); if (!done) { request(100); } } if (done) { latch.countDown(); } } }); latch.await(); System.out.println( "testUserSubscriberUsingRequestAsync => Received: " + totalReceived.get() + " Emitted: " + c.get() + " Request Batches: " + batches.get()); assertEquals(2000, c.get()); assertEquals(2000, totalReceived.get()); assertEquals(20, batches.get()); }