@Override public void run() { try { doProcess(); } catch (InitializationException ex) { logger.error("Exception: ", ex); setStatus(ex.getMessage()); setError(ex); callbackListener.actionCompleted(false); } catch (NoRepositoryFoundException ex) { logger.error("Exception: ", ex); setStatus(resourceBundle.getString("reptest_nothing_found") + ex.getMessage()); setError(ex); callbackListener.actionCompleted(false); } catch (StorageException ex) { logger.error("Exception: ", ex); setStatus(resourceBundle.getString("reptest_connection_status_fail") + ex.getMessage()); setError(ex); callbackListener.actionCompleted(false); } catch (Exception ex) { logger.error("Exception: ", ex); setStatus(ex.getMessage()); setError(ex); callbackListener.actionCompleted(false); } }
// Test event queuing and dequeuing during broadcasting public void testEventBroadcasting() { // Register a listener that will conditionally queue a new event UIViewRoot root = facesContext.getApplication().getViewHandler().createView(facesContext, null); facesContext.setViewRoot(root); root.addFacesListener(new TestListener("t", "2", "4")); TestListener.trace(null); // Queue some events, including the trigger one TestEvent event = new TestEvent(root, "1"); event.setPhaseId(PhaseId.APPLY_REQUEST_VALUES); root.queueEvent(event); event = new TestEvent(root, "2"); event.setPhaseId(PhaseId.APPLY_REQUEST_VALUES); root.queueEvent(event); event = new TestEvent(root, "3"); event.setPhaseId(PhaseId.APPLY_REQUEST_VALUES); root.queueEvent(event); // Simulate the Apply Request Values phase root.processDecodes(facesContext); // Validate the results (expect 4th event to also be queued) String expected = "/t/1/t/2/t/3/t/4"; assertEquals(expected, TestListener.trace()); }
/** * Test calls the method. * * <p>Has <b> OK </b> status if the method successfully returns and no exceptions were thrown. * * <p>The following method tests are to be completed successfully before : * * <ul> * <li><code> addApproveActionListener() </code> : adds listener to an object * </ul> */ public void _removeApproveActionListener() { requiredMethod("addApproveActionListener()"); listener.init(); listener.approve = true; oObj.removeApproveActionListener(listener); tRes.tested("removeApproveActionListener()", true); }
@Test(expected = CancellationException.class, timeout = 1000L) public void testWaitCancel() throws ExecutionException, InterruptedException { Executor executor = Executors.newSingleThreadExecutor(); TestListener<Integer> listener = new TestListener<Integer>(); final ListenableFutureTask<Integer> future = new ListenableFutureTask<Integer>( new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(1000000); return 0; } }); future.addListener(listener); executor.execute(future); new Thread( new Runnable() { @Override public void run() { future.cancel(true); } }) .start(); try { future.get(); Assert.fail("get() succeeded"); } finally { Assert.assertTrue(listener.waitValue() instanceof CancellationException); } }
private void checkEventQueueing(PhaseId phaseId) { // NOTE: Current semantics for ANY_PHASE listeners is that // the event should be delivered exactly once, so the existence // of such a listener does not cause the event to remain queued. // Therefore, the expected string is the same as for any // phase-specific listener, and it should get matched after // Apply Request Values processing since that is first phase // for which events are fired // Register an event listener for the specified phase id UIViewRoot root = facesContext.getApplication().getViewHandler().createView(facesContext, null); facesContext.setViewRoot(root); TestEvent event = null; TestListener listener = new TestListener("t"); root.addFacesListener(listener); // Queue some events to be processed event = new TestEvent(root, "1"); event.setPhaseId(phaseId); root.queueEvent(event); event = new TestEvent(root, "2"); event.setPhaseId(phaseId); root.queueEvent(event); String expected = "/t/1/t/2"; // Fire off the relevant lifecycle methods and check expected results TestListener.trace(null); assertEquals("", TestListener.trace()); root.processDecodes(facesContext); if (PhaseId.APPLY_REQUEST_VALUES.equals(phaseId) || PhaseId.ANY_PHASE.equals(phaseId)) { assertEquals(expected, TestListener.trace()); } else { assertEquals("", TestListener.trace()); } root.processValidators(facesContext); if (PhaseId.PROCESS_VALIDATIONS.equals(phaseId) || PhaseId.APPLY_REQUEST_VALUES.equals(phaseId) || PhaseId.APPLY_REQUEST_VALUES.equals(phaseId) || PhaseId.ANY_PHASE.equals(phaseId)) { assertEquals(expected, TestListener.trace()); } else { assertEquals("", TestListener.trace()); } root.processUpdates(facesContext); if (PhaseId.UPDATE_MODEL_VALUES.equals(phaseId) || PhaseId.PROCESS_VALIDATIONS.equals(phaseId) || PhaseId.APPLY_REQUEST_VALUES.equals(phaseId) || PhaseId.ANY_PHASE.equals(phaseId)) { assertEquals(expected, TestListener.trace()); } else { assertEquals("", TestListener.trace()); } root.processApplication(facesContext); assertEquals(expected, TestListener.trace()); }
@Test public void testFailManualFix() throws InterruptedException { listener.reset(11, 0, 0); tasks.fail("T2"); tasks.run(); assertThat(listener.stateChangedLatch.await(6, TimeUnit.SECONDS), is(true)); Map<Object, Object> variables = machine.getExtendedState().getVariables(); assertThat(variables.size(), is(3)); assertThat(machine.getState().getIds(), contains(States.ERROR, States.MANUAL)); listener.reset(1, 0, 0); tasks.fix(); assertThat(listener.stateChangedLatch.await(6, TimeUnit.SECONDS), is(true)); assertThat(machine.getState().getIds(), contains(States.READY)); }
/** * Moves the window to front and check the listener calls. * * <p>Has <b>OK</b> status if listener <code>activated</code> method was called. */ public void _toFront() { requiredMethod("addTopWindowListener()"); listener.initListener(); oObj.toFront(); waitForEventIdle(); tRes.tested("toFront()", listener.activated && !listener.deactivated); }
@Test public void testRunTwice() throws InterruptedException { listener.reset(9, 0, 0); tasks.run(); assertThat(listener.stateChangedLatch.await(6, TimeUnit.SECONDS), is(true)); assertThat(machine.getState().getIds(), contains(States.READY)); Map<Object, Object> variables = machine.getExtendedState().getVariables(); assertThat(variables.size(), is(3)); listener.reset(9, 0, 0); tasks.run(); assertThat(listener.stateChangedLatch.await(6, TimeUnit.SECONDS), is(true)); assertThat(machine.getState().getIds(), contains(States.READY)); variables = machine.getExtendedState().getVariables(); assertThat(variables.size(), is(3)); }
@Test(timeout = 1000L) public void testWaitSuccess() throws ExecutionException, InterruptedException { Executor executor = Executors.newSingleThreadExecutor(); TestListener<Integer> listener = new TestListener<Integer>(); ListenableFutureTask<Integer> future = new ListenableFutureTask<Integer>( new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(1); return 1; } }); future.addListener(listener); executor.execute(future); Assert.assertEquals(1, (int) future.get()); Assert.assertEquals(1, (int) (Integer) listener.waitValue()); }
@Test public void testFailAutomaticFix() throws InterruptedException { listener.reset(11, 0, 0); tasks.fail("T1"); tasks.run(); assertThat(listener.stateChangedLatch.await(6, TimeUnit.SECONDS), is(true)); assertThat(listener.stateChangedCount, is(11)); assertThat(machine.getState().getIds(), contains(States.READY)); }
public void onConnectionClosed() { System.out.println( m_session.getLocalAddress() + " -> " + m_session.getRemoteAddress() + " [TEST1]: connection closed, processed " + m_processedMessages + " messages."); super.onConnectionClosed(); }
@Test public void testStop() throws Exception { TestLifeCycle lifecycle = new TestLifeCycle(); TestListener listener = new TestListener(); lifecycle.addLifeCycleListener(listener); // need to set the state to something other than stopped or stopping or // else // stop() will return without doing anything lifecycle.start(); lifecycle.setCause(cause); try { ((StdErrLog) Log.getLogger(AbstractLifeCycle.class)).setHideStacks(true); lifecycle.stop(); assertTrue(false); } catch (Exception e) { assertEquals(cause, e); assertEquals(cause, listener.getCause()); } finally { ((StdErrLog) Log.getLogger(AbstractLifeCycle.class)).setHideStacks(false); } lifecycle.setCause(null); lifecycle.stop(); // check that the stopping event has been thrown assertTrue("The stopping event didn't occur", listener.stopping); // check that the stopped event has been thrown assertTrue("The stopped event didn't occur", listener.stopped); // check that the stopping event occurs before the stopped event assertTrue( "The stopping event must occur before the stopped event", listener.stoppingTime <= listener.stoppedTime); // System.out.println("STOPING TIME : " + listener.stoppingTime + " : " + listener.stoppedTime); // check that the lifecycle's state is stopped assertTrue("The lifecycle state is not stooped", lifecycle.isStopped()); }
// Test AbortProcessingException support public void testAbortProcessingException() { // Register three listeners, with the second one set to abort UIViewRoot root = facesContext.getApplication().getViewHandler().createView(facesContext, null); facesContext.setViewRoot(root); root.addFacesListener(new TestListener("a", false)); root.addFacesListener(new TestListener("b", true)); root.addFacesListener(new TestListener("c", false)); // Queue two event and check the results TestListener.trace(null); TestEvent event1 = new TestEvent(root, "1"); event1.setPhaseId(PhaseId.APPLY_REQUEST_VALUES); root.queueEvent(event1); TestEvent event2 = new TestEvent(root, "2"); event2.setPhaseId(PhaseId.APPLY_REQUEST_VALUES); root.queueEvent(event2); root.processDecodes(facesContext); assertEquals("/a/1/b/1/a/2/b/2", TestListener.trace()); }
@Test(expected = ExecutionException.class, timeout = 1000L) public void testWaitFailure() throws ExecutionException, InterruptedException { Executor executor = Executors.newSingleThreadExecutor(); TestListener<Integer> listener = new TestListener<Integer>(); ListenableFutureTask<Integer> future = new ListenableFutureTask<Integer>( new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(1); throw new TestingRuntimeException(); } }); future.addListener(listener); executor.execute(future); try { future.get(); Assert.fail("get() succeeded"); } finally { Assert.assertTrue(listener.waitValue() instanceof TestingRuntimeException); } }
@SuppressWarnings({"unchecked"}) @Test public void testTriggerlessTransition() throws Exception { context.register(BaseConfig.class, Config1.class); context.refresh(); assertTrue(context.containsBean(StateMachineSystemConstants.DEFAULT_ID_STATEMACHINE)); ObjectStateMachine<TestStates, TestEvents> machine = context.getBean( StateMachineSystemConstants.DEFAULT_ID_STATEMACHINE, ObjectStateMachine.class); TestListener listener = new TestListener(); machine.addStateListener(listener); machine.start(); assertThat(machine.getState().getIds(), contains(TestStates.S1)); listener.reset(2); machine.sendEvent(MessageBuilder.withPayload(TestEvents.E1).build()); assertThat(listener.stateChangedLatch.await(2, TimeUnit.SECONDS), is(true)); assertThat(listener.stateChangedCount, is(2)); assertThat(machine.getState().getIds(), contains(TestStates.S3)); }
@Test public void testStart() throws Exception { TestLifeCycle lifecycle = new TestLifeCycle(); TestListener listener = new TestListener(); lifecycle.addLifeCycleListener(listener); lifecycle.setCause(cause); try { StdErrLog.getLogger(AbstractLifeCycle.class).setHideStacks(true); lifecycle.start(); assertTrue(false); } catch (Exception e) { assertEquals(cause, e); assertEquals(cause, listener.getCause()); } finally { StdErrLog.getLogger(AbstractLifeCycle.class).setHideStacks(false); } lifecycle.setCause(null); lifecycle.start(); // check that the starting event has been thrown assertTrue("The staring event didn't occur", listener.starting); // check that the started event has been thrown assertTrue("The started event didn't occur", listener.started); // check that the starting event occurs before the started event assertTrue( "The starting event must occur before the started event", listener.startingTime <= listener.startedTime); // check that the lifecycle's state is started assertTrue("The lifecycle state is not started", lifecycle.isStarted()); }
@Override public void insertAction(Action action) { if (listener != null) { listener.sendBackAction(action); } }
/** * Runs a query twice, with native crossjoin optimization enabled and disabled. If both results * are equal,and both aggree with the expected result, it is considered correct. * * <p>Optionally the query can be run with fresh connection. This is useful if the test case sets * its certain mondrian properties, e.g. native properties like: mondrian.native.filter.enable * * @param resultLimit Maximum result size of all the MDX operations in this query. This might be * hard to estimate as it is usually larger than the rowCount of the final result. Setting it * to 0 will cause this limit to be ignored. * @param rowCount Number of rows returned. (That is, the number of positions on the last axis of * the query.) * @param mdx Query * @param expectedResult Expected result string * @param freshConnection Whether fresh connection is required */ protected void checkNative( int resultLimit, int rowCount, String mdx, String expectedResult, boolean freshConnection) { // Don't run the test if we're testing expression dependencies. // Expression dependencies cause spurious interval calls to // 'level.getMembers()' which create false negatives in this test. if (MondrianProperties.instance().TestExpDependencies.get() > 0) { return; } getConnection().getCacheControl(null).flushSchemaCache(); try { Logger.getLogger(getClass()).debug("*** Native: " + mdx); boolean reuseConnection = !freshConnection; Connection con = getTestContext().withSchemaPool(reuseConnection).getConnection(); RolapNativeRegistry reg = getRegistry(con); reg.useHardCache(true); TestListener listener = new TestListener(); reg.setListener(listener); reg.setEnabled(true); TestCase c = new TestCase(con, resultLimit, rowCount, mdx); Result result = c.run(); String nativeResult = TestContext.toString(result); if (!listener.isFoundEvaluator()) { fail("expected native execution of " + mdx); } if (!listener.isExecuteSql()) { fail("cache is empty: expected SQL query to be executed"); } if (MondrianProperties.instance().EnableRolapCubeMemberCache.get()) { // run once more to make sure that the result comes from cache // now listener.setExecuteSql(false); c.run(); if (listener.isExecuteSql()) { fail("expected result from cache when query runs twice"); } } con.close(); Logger.getLogger(getClass()).debug("*** Interpreter: " + mdx); getConnection().getCacheControl(null).flushSchemaCache(); con = getTestContext().withSchemaPool(false).getConnection(); reg = getRegistry(con); listener.setFoundEvaluator(false); reg.setListener(listener); // disable RolapNativeSet reg.setEnabled(false); result = executeQuery(mdx, con); String interpretedResult = TestContext.toString(result); if (listener.isFoundEvaluator()) { fail("did not expect native executions of " + mdx); } if (expectedResult != null) { TestContext.assertEqualsVerbose( expectedResult, nativeResult, false, "Native implementation returned different result than " + "expected; MDX=" + mdx); TestContext.assertEqualsVerbose( expectedResult, interpretedResult, false, "Interpreter implementation returned different result than " + "expected; MDX=" + mdx); } if (!nativeResult.equals(interpretedResult)) { TestContext.assertEqualsVerbose( interpretedResult, nativeResult, false, "Native implementation returned different result than " + "interpreter; MDX=" + mdx); } } finally { Connection con = getConnection(); RolapNativeRegistry reg = getRegistry(con); reg.setEnabled(true); reg.useHardCache(false); } }
@Test public void testOutOfStock() { // Conversation manager must be sharable, as could be specific to // conversation engine, but may also be based on a persistent // central repository ConversationManager cm = new DefaultConversationManager(); DefaultParticipantRegistry pr = new DefaultParticipantRegistry(); DefaultMessagingLayer ml = new DefaultMessagingLayer(); java.security.Principal gary = new KerberosPrincipal("*****@*****.**"); pr.addParticipant(new DefaultParticipant(PurchasingSeller.INSTANCE.getRole(), gary)); pr.addParticipant(new DefaultParticipant(PurchasingCreditAgency.INSTANCE.getRole(), gary)); DefaultConversationEngine ce1 = new DefaultConversationEngine(); Set<ConversationType> cts1 = new HashSet<ConversationType>(); cts1.add(PurchasingBuyer.INSTANCE); cts1.add(PurchasingSeller.INSTANCE); ce1.setConversationTypes(cts1); ce1.setPrincipal(gary); ce1.setConversationManager(cm); ce1.setParticipantRegistry(pr); ce1.setMessagingLayer(ml); ml.init(ce1); TestListener tl1 = new TestListener("ce1"); ce1.setListener(tl1); DefaultConversationEngine ce2 = new DefaultConversationEngine(); Set<ConversationType> cts2 = new HashSet<ConversationType>(); cts2.add(PurchasingCreditAgency.INSTANCE); ce2.setConversationTypes(cts2); ce2.setPrincipal(gary); ce2.setConversationManager(cm); ce2.setParticipantRegistry(pr); ce2.setMessagingLayer(ml); ml.init(ce2); TestListener tl2 = new TestListener("ce2"); ce2.setListener(tl2); ConversationId cid = new DefaultConversationId("1"); java.util.Map<String, Object> vars = new java.util.HashMap<String, Object>(); vars.put("product", "car"); vars.put("price", 150); ce1.createConversation(cid, PurchasingBuyer.INSTANCE, vars); if (tl1.getStartedCount() != 2) { fail("Start count should be 2: " + tl1.getStartedCount()); } if (tl1.getSendingCount() != 2) { fail("Sending count should be 2: " + tl1.getSendingCount()); } if (tl1.getReceivedCount() != 2) { fail("Received count should be 2: " + tl1.getReceivedCount()); } if (tl1.getFinishedCount() != 2) { fail("Finished count should be 2: " + tl1.getFinishedCount()); } if (tl2.getStartedCount() != 0) { fail("Start count should be 0: " + tl2.getStartedCount()); } if (tl2.getSendingCount() != 0) { fail("Sending count should be 0: " + tl2.getSendingCount()); } if (tl2.getReceivedCount() != 0) { fail("Received count should be 0: " + tl2.getReceivedCount()); } if (tl2.getFinishedCount() != 0) { fail("Finished count should be 0: " + tl2.getFinishedCount()); } }
private void assertWasNotRun(Class<?> testClass) { assertFalse( testClass.getName() + " expected not to have been started but was", testListener.wasRun(testClass)); }
private void assertWasRun(Class<?> testClass) { assertTrue( testClass.getName() + " expected to finish but did not", testListener.wasRun(testClass)); }
@Test public void testSomeBasics() throws Exception { ZooKeeperItf zk1 = ZkUtil.connect("localhost:" + ZK_CLIENT_PORT, 3000); ZooKeeperItf zk2 = ZkUtil.connect("localhost:" + ZK_CLIENT_PORT, 3000); WriteableIndexerModel model1 = null; WriteableIndexerModel model2 = null; try { TestListener listener = new TestListener(); model1 = new IndexerModelImpl(zk1); model1.registerListener(listener); // Create an index IndexDefinition index1 = model1.newIndex("index1"); index1.setConfiguration("<indexer/>".getBytes("UTF-8")); index1.setSolrShards(Collections.singletonMap("shard1", "http://localhost:8983/solr")); model1.addIndex(index1); listener.waitForEvents(1); listener.verifyEvents(new IndexerModelEvent(IndexerModelEventType.INDEX_ADDED, "index1")); // Verify that a fresh indexer model has the index model2 = new IndexerModelImpl(zk2); assertEquals(1, model2.getIndexes().size()); assertTrue(model2.hasIndex("index1")); // Update the index index1.setGeneralState(IndexGeneralState.DISABLED); String lock = model1.lockIndex("index1"); model1.updateIndex(index1, lock); listener.waitForEvents(1); listener.verifyEvents(new IndexerModelEvent(IndexerModelEventType.INDEX_UPDATED, "index1")); // Do not release the lock, updating through model2 should fail index1.setConfiguration("<indexer></indexer>".getBytes("UTF-8")); try { model2.updateIndex(index1, lock + "foo"); fail("expected exception"); } catch (IndexUpdateException e) { // verify the exception says something about locks assertTrue(e.getMessage().indexOf("lock") != -1); } model1.unlockIndex(lock); model1.deleteIndex("index1"); listener.waitForEvents(1); listener.verifyEvents(new IndexerModelEvent(IndexerModelEventType.INDEX_REMOVED, "index1")); // Create some more indexes IndexerModelEvent[] expectedEvents = new IndexerModelEvent[9]; for (int i = 2; i <= 10; i++) { String name = "index" + i; IndexDefinition index = model1.newIndex(name); index.setConfiguration("<indexer/>".getBytes("UTF-8")); index.setSolrShards(Collections.singletonMap("shard1", "http://localhost:8983/solr")); model1.addIndex(index); expectedEvents[i - 2] = new IndexerModelEvent(IndexerModelEventType.INDEX_ADDED, name); } listener.waitForEvents(9); listener.verifyEvents(expectedEvents); } finally { Closer.close(model1); Closer.close(model2); Closer.close(zk1); Closer.close(zk2); } }
@Override protected void onPostExecute(String result) { listener.onPostTest(result); }
@Override protected void onPreExecute() { listener.onPreTest(); }