public void testQualifiedLookup() {
    final QualA qualA =
        new QualA() {
          @Override
          public Class<? extends Annotation> annotationType() {
            return QualA.class;
          }
        };

    final QualB qualB =
        new QualB() {
          @Override
          public Class<? extends Annotation> annotationType() {
            return QualB.class;
          }
        };

    final Collection<SyncBeanDef<CommonInterface>> beans =
        IOC.getBeanManager().lookupBeans(CommonInterface.class);
    assertEquals("wrong number of beans", 2, beans.size());

    final SyncBeanDef<CommonInterface> beanA =
        IOC.getBeanManager().lookupBean(CommonInterface.class, qualA);
    assertNotNull("no bean found", beanA);
    assertTrue("wrong bean looked up", beanA.getInstance() instanceof QualAppScopeBeanA);

    final SyncBeanDef<CommonInterface> beanB =
        IOC.getBeanManager().lookupBean(CommonInterface.class, qualB);
    assertNotNull("no bean found", beanB);
    assertTrue("wrong bean looked up", beanB.getInstance() instanceof QualAppScopeBeanB);
  }
  public void testQualifiedLookupFailure() {
    final LincolnBar wrongAnno =
        new LincolnBar() {
          @Override
          public Class<? extends Annotation> annotationType() {
            return LincolnBar.class;
          }
        };

    try {
      final SyncBeanDef<CommonInterface> bean =
          IOC.getBeanManager().lookupBean(CommonInterface.class, anyAnno);
      fail("should have thrown an exception, but got: " + bean);
    } catch (IOCResolutionException e) {
      assertTrue(
          "wrong exception thrown: " + e.getMessage(),
          e.getMessage().contains("Multiple beans matched"));
    }

    try {
      final SyncBeanDef<CommonInterface> bean =
          IOC.getBeanManager().lookupBean(CommonInterface.class, wrongAnno);
      fail("should have thrown an exception, but got: " + bean);
    } catch (IOCResolutionException e) {
      assertTrue(
          "wrong exception thrown: " + e.getMessage(), e.getMessage().contains("No beans matched"));
    }
  }
  public void testBeanManagerLookupForExtendedInterfaceType() {
    // This should find ApplicationScopedBeanA, ApplicationScopedBeanB and ApplicationScopedBeanC
    final Collection<SyncBeanDef<InterfaceRoot>> beans =
        IOC.getBeanManager().lookupBeans(InterfaceRoot.class);
    assertEquals(
        "did not find all managed implementations of " + InterfaceRoot.class.getName(),
        3,
        beans.size());

    // This should find ApplicationScopedBeanA and ApplicationScopedBeanB (InterfaceB extends
    // InterfaceA)
    final Collection<SyncBeanDef<InterfaceA>> beansB =
        IOC.getBeanManager().lookupBeans(InterfaceA.class);
    assertEquals(
        "did not find both managed implementations of " + InterfaceA.class.getName(),
        2,
        beansB.size());

    // This should find only ApplicationScopedBeanB
    final Collection<SyncBeanDef<InterfaceB>> beansC =
        IOC.getBeanManager().lookupBeans(InterfaceB.class);
    assertEquals(
        "did not find exactly one managed implementation of " + InterfaceB.class.getName(),
        1,
        beansC.size());
  }
  public void testBeanManagerLookupForOuterInterfacesOfNonAbstractType() {
    final SyncBeanDef<InterfaceC> beanC = IOC.getBeanManager().lookupBean(InterfaceC.class);
    assertNotNull("did not find any beans matching", beanC);

    final SyncBeanDef<InterfaceD> beanD = IOC.getBeanManager().lookupBean(InterfaceD.class);
    assertNotNull("did not find any beans matching", beanD);
  }
  public void testReportedScopeCorrect() {
    final SyncBeanDef<ApplicationScopedBean> appScopeBean =
        IOC.getBeanManager().lookupBean(ApplicationScopedBean.class);
    final SyncBeanDef<DependentScopedBean> dependentIOCBean =
        IOC.getBeanManager().lookupBean(DependentScopedBean.class);

    assertEquals(ApplicationScoped.class, appScopeBean.getScope());
    assertEquals(Dependent.class, dependentIOCBean.getScope());
  }
  public void testDestructionCallbackStopSyncWorker() {
    delayTestFinish(45000);

    final List<SyncResponse<SimpleEntity>> expectedSyncResponses =
        new ArrayList<SyncResponse<SimpleEntity>>();

    // replace the caller so we can see what the SyncWorker asks its ClientSyncManager to do
    csm.dataSyncService =
        new Caller<DataSyncService>() {

          @Override
          public DataSyncService call(final RemoteCallback<?> callback) {
            return new DataSyncService() {

              @SuppressWarnings({"unchecked", "rawtypes"})
              @Override
              public <X> List<SyncResponse<X>> coldSync(
                  SyncableDataSet<X> dataSet, List<SyncRequestOperation<X>> actualClientRequests) {
                System.out.println("Short-circuiting DataSyncService call:");
                System.out.println("   dataSet = " + dataSet);
                System.out.println("   actualClientRequests = " + actualClientRequests);

                RemoteCallback rawRemoteCallback = callback;
                rawRemoteCallback.callback(expectedSyncResponses);

                return null; // this is the Caller stub. it doesn't return the value directly.
              }
            };
          }

          @Override
          public DataSyncService call(
              final RemoteCallback<?> callback, final ErrorCallback<?> errorCallback) {
            return call(callback);
          }

          @Override
          public DataSyncService call() {
            fail("Unexpected use of callback");
            return null; // NOTREACHED
          }
        };

    syncBean = IOC.getBeanManager().lookupBean(DependentScopedSyncBean.class).getInstance();
    IOC.getBeanManager().destroyBean(syncBean);

    new Timer() {
      @Override
      public void run() {
        assertEquals(0, syncBean.getCallbackCount());
        syncBean = null;
        finishTest();
      }
    }.schedule(7000);
  }
  public void testQualifierLookupWithAnnoAttribFailure() {
    final QualV qualOrange =
        new QualV() {
          @Override
          public QualEnum value() {
            return QualEnum.ORANGES;
          }

          @Override
          public Class<? extends Annotation> annotationType() {
            return QualV.class;
          }

          @Override
          public int amount() {
            return 5;
          }
        };

    final QualV qualApple =
        new QualV() {
          @Override
          public QualEnum value() {
            return QualEnum.APPLES;
          }

          @Override
          public Class<? extends Annotation> annotationType() {
            return QualV.class;
          }

          @Override
          public int amount() {
            return 6;
          }
        };

    final Collection<SyncBeanDef<CommonInterfaceB>> beans =
        IOC.getBeanManager().lookupBeans(CommonInterfaceB.class);
    assertEquals("wrong number of beans", 2, beans.size());

    final SyncBeanDef<CommonInterfaceB> beanA =
        IOC.getBeanManager().lookupBean(CommonInterfaceB.class, qualOrange);
    assertNotNull("no bean found", beanA);
    assertFalse("wrong bean looked up", beanA.getInstance() instanceof QualParmAppScopeBeanApples);

    final SyncBeanDef<CommonInterfaceB> beanB =
        IOC.getBeanManager().lookupBean(CommonInterfaceB.class, qualApple);
    assertNotNull("no bean found", beanB);
    assertFalse("wrong bean looked up", beanB.getInstance() instanceof QualParmAppScopeBeanOranges);
  }
 @Override
 public void dispose() {
   onRenameCommand.clear();
   onDeleteCommand.clear();
   onUpdateCommand.clear();
   onCopyCommand.clear();
   onConcurrentRenameCommand.clear();
   onConcurrentDeleteCommand.clear();
   onConcurrentUpdateCommand.clear();
   onConcurrentCopyCommand.clear();
   if (IOC.getBeanManager() != null) {
     IOC.getBeanManager().destroyBean(this);
   }
 }
  @Override
  protected void gwtTearDown() throws Exception {
    assertFalse(
        "ClientSyncManager 'sync in progress' flag got stuck on true", csm.isSyncInProgress());

    if (syncBean != null) {
      IOC.getBeanManager().destroyBean(syncBean);
    }

    Container.reset();
    IOC.reset();
    InitVotes.reset();
    setRemoteCommunicationEnabled(true);
    super.gwtTearDown();
  }
 public void testCallerUsesShadowServiceIfRemoteEndpointDoesntExist() {
   runAfterInit(
       () -> {
         final Greeter greeter = IOC.getBeanManager().lookupBean(Greeter.class).getInstance();
         final CallerBean callerBean =
             IOC.getBeanManager().lookupBean(CallerBean.class).getInstance();
         callerBean
             .getOfflineServiceCaller()
             .call(
                 (r) -> {
                   assertEquals(greeter.offline(), r);
                   finishTest();
                 })
             .greeting();
       });
 }
Exemple #11
0
  private void init() {
    // The AsyncBeanManager API works in both synchronous and asynchronous IOC mode
    AsyncBeanManager bm = IOC.getAsyncBeanManager();

    // In the case that this method is executed before the first call has successfully processed all
    // of its callbacks, we must cancel those uncompleted callbacks in flight to prevent duplicate
    // data in the ListWidget.
    for (WidgetCreationalCallback callback : callbacks) {
      callback.discard();
    }
    callbacks.clear();
    pendingCallbacks = 0;

    // clean up the old widgets before we add new ones (this will eventually become a feature of the
    // framework: ERRAI-375)
    Iterator<Widget> it = panel.iterator();
    while (it.hasNext()) {
      bm.destroyBean(it.next());
      it.remove();
    }

    if (items == null) return;

    pendingCallbacks = items.size();
    AsyncBeanDef<W> itemBeanDef = bm.lookupBean(getItemWidgetType());
    for (final M item : items) {
      final WidgetCreationalCallback callback = new WidgetCreationalCallback(item);
      callbacks.add(callback);
      itemBeanDef.newInstance(callback);
    }
  }
 public void testCallerUsesRemoteEndpointIfBusConnected() {
   runAfterInit(
       () -> {
         final Greeter greeter = IOC.getBeanManager().lookupBean(Greeter.class).getInstance();
         final CallerBean callerBean =
             IOC.getBeanManager().lookupBean(CallerBean.class).getInstance();
         callerBean
             .getOnlineServiceCaller()
             .call(
                 (r) -> {
                   assertEquals(greeter.online(), r);
                   finishTest();
                 })
             .greeting();
       });
 }
  public void testLookupAllBeansQualified() {
    final Collection<SyncBeanDef<Object>> beans =
        IOC.getBeanManager().lookupBeans(Object.class, QUAL_A);

    assertEquals(1, beans.size());
    assertEquals(QualAppScopeBeanA.class, beans.iterator().next().getBeanClass());
  }
  public void testBeanManagerAPIs() {
    final SyncBeanManager mgr = IOC.getBeanManager();
    final SyncBeanDef<QualAppScopeBeanA> bean = mgr.lookupBean(QualAppScopeBeanA.class, anyAnno);

    final Set<Annotation> a = bean.getQualifiers();
    assertEquals("there should be two qualifiers", 2, a.size());
    assertTrue("wrong qualifiers", annotationSetMatches(a, QualA.class, Any.class));
  }
  /**
   * Tests that beans marked as Dependent scoped by an IOCExtension can still be forced into a
   * different scope (in this case, ApplicationScoped) when they are annotated as such.
   *
   * <p>Besides this being a good idea on its own, both Errai UI Templates and Errai Navigation rely
   * on this behaviour.
   */
  public void testNormalScopeOverridesDependent() {
    final FoobieScopedBean foobieScopedBean1 =
        IOC.getBeanManager().lookupBean(FoobieScopedBean.class).getInstance();
    final FoobieScopedBean foobieScopedBean2 =
        IOC.getBeanManager().lookupBean(FoobieScopedBean.class).getInstance();

    assertNotNull(foobieScopedBean1);
    assertNotSame(foobieScopedBean1, foobieScopedBean2);

    final FoobieScopedOverriddenBean foobieScopedOverriddenBean1 =
        IOC.getBeanManager().lookupBean(FoobieScopedOverriddenBean.class).getInstance();

    final FoobieScopedOverriddenBean foobieScopedOverriddenBean2 =
        IOC.getBeanManager().lookupBean(FoobieScopedOverriddenBean.class).getInstance();

    assertNotNull(foobieScopedOverriddenBean1);
    assertSame(foobieScopedOverriddenBean1, foobieScopedOverriddenBean2);
  }
  public void testCallerUsesShadowServiceIfBusNotConnected() {
    runAfterInit(
        () -> {
          ((ClientMessageBusImpl) ErraiBus.get()).setState(BusState.CONNECTION_INTERRUPTED);

          final Greeter greeter = IOC.getBeanManager().lookupBean(Greeter.class).getInstance();
          final CallerBean callerBean =
              IOC.getBeanManager().lookupBean(CallerBean.class).getInstance();
          callerBean
              .getOnlineServiceCaller()
              .call(
                  (r) -> {
                    assertEquals(greeter.offline(), r);
                    finishTest();
                  })
              .greeting();
        });
  }
 protected List<LayoutDragComponent> lookupPerspectiveDragComponents() {
   List<LayoutDragComponent> result = new ArrayList<LayoutDragComponent>();
   Collection<IOCBeanDef<PerspectiveEditorDragComponent>> beanDefs =
       IOC.getBeanManager().lookupBeans(PerspectiveEditorDragComponent.class);
   for (IOCBeanDef<PerspectiveEditorDragComponent> beanDef : beanDefs) {
     PerspectiveEditorDragComponent dragComponent = beanDef.getInstance();
     result.add(dragComponent);
   }
   return result;
 }
  public void testLookupByName() {
    final Collection<SyncBeanDef> beans = IOC.getBeanManager().lookupBeans("animal");

    assertEquals("wrong number of beans", 2, beans.size());
    assertTrue("should contain a pig", containsInstanceOf(beans, Pig.class));
    assertTrue("should contain a cow", containsInstanceOf(beans, Cow.class));

    for (SyncBeanDef<?> bean : beans) {
      assertEquals("animal", bean.getName());
    }
  }
  public void testBeanManagerLookupBeanFromAbstractRootType() {
    final SyncBeanDef<AbstractBean> bean = IOC.getBeanManager().lookupBean(AbstractBean.class);
    assertNotNull("did not find any beans matching", bean);

    final AbstractBean beanInst = bean.getInstance();
    assertNotNull("bean instance is null", beanInst);

    assertTrue(
        "bean is incorrect instance: " + beanInst.getClass(),
        beanInst instanceof InheritedFromAbstractBean);
  }
 public void testNameAvailableThroughInterfaceLookup() {
   Collection<SyncBeanDef<CreditCard>> beans = IOC.getBeanManager().lookupBeans(CreditCard.class);
   for (SyncBeanDef<CreditCard> bean : beans) {
     if (bean.getBeanClass().getName().endsWith("Visa")) {
       assertEquals("visa", bean.getName());
     } else if (bean.getBeanClass().getName().endsWith("Amex")) {
       assertEquals("amex", bean.getName());
     } else {
       fail("Unexpected bean was returned from lookup: " + bean);
     }
   }
 }
Exemple #21
0
 private void addWidget(final M m) {
   // This call is always synchronous, since the list can only be manipulated after
   // onItemsRendered was called. At that point the code of a potential split point must have
   // already been downloaded.
   AsyncBeanDef<W> itemBeanDef = IOC.getAsyncBeanManager().lookupBean(getItemWidgetType());
   itemBeanDef.getInstance(
       new CreationalCallback<W>() {
         @Override
         public void callback(W widget) {
           widget.setModel(m);
           panel.add(widget);
         }
       });
 }
  public void testAddingProgrammaticDestructionCallback() {
    final DependentScopedBean dependentScopedBean =
        IOC.getBeanManager().lookupBean(DependentScopedBean.class).newInstance();

    class TestValueHolder {
      boolean destroyed = false;
    }

    final TestValueHolder testValueHolder = new TestValueHolder();

    IOC.getBeanManager()
        .addDestructionCallback(
            dependentScopedBean,
            new DestructionCallback<Object>() {
              @Override
              public void destroy(Object bean) {
                testValueHolder.destroyed = true;
              }
            });

    IOC.getBeanManager().destroyBean(dependentScopedBean);

    assertEquals(true, testValueHolder.destroyed);
  }
  @Test
  public void testShouldCreateLocaleListBoxContainingAllLanguageOptions() {
    // given
    LocaleSelector selector = IOC.getBeanManager().lookupBean(LocaleSelector.class).getInstance();
    LocaleListBox localeListBox = app.getComponent().getListBox();
    localeListBox.init();

    // when - then
    assertNull(localeListBox.getValue());
    assertEquals(4, selector.getSupportedLocales().size());

    localeListBox.setValue(new Locale("da", "Danish"), true);

    assertEquals("da", TranslationService.currentLocale());
    assertNotNull(localeListBox.getValue());
  }
  public void testShadowServiceAsMessageCallback() {
    runAfterInit(
        () -> {
          final OfflineMessageCallback callback =
              IOC.getBeanManager().lookupBean(OfflineMessageCallback.class).getInstance();
          assertNull(callback.getGreeting());

          MessageBuilder.createMessage()
              .toSubject("Greeting")
              .signalling()
              .with("greeting", "Hello, there")
              .noErrorHandling()
              .sendNowWith(ErraiBus.get());

          assertNotNull(callback.getGreeting());
          assertEquals("Hello, there", callback.getGreeting());
          finishTest();
        });
  }
  public void testBeanManagerLookupInheritedScopeBean() {
    final SyncBeanDef<InheritedApplicationScopedBean> bean =
        IOC.getBeanManager().lookupBean(InheritedApplicationScopedBean.class, anyAnno);
    assertNotNull("inherited application scoped bean did not lookup", bean);

    final InheritedApplicationScopedBean beanInst = bean.getInstance();
    assertNotNull("bean instance is null", beanInst);

    final DependentScopedBean bean1 = beanInst.getBean1();
    assertNotNull("bean1 is null", bean1);

    final DependentScopedBeanWithDependencies beanWithDependencies =
        beanInst.getBeanWithDependencies();
    assertNotNull("beanWithDependencies is null", beanWithDependencies);

    final DependentScopedBean bean2 = beanWithDependencies.getBean();
    assertNotSame("bean1 and bean2 should be different", bean1, bean2);

    final InheritedApplicationScopedBean beanInst2 = bean.getInstance();
    assertSame("bean is not observing application scope", beanInst, beanInst2);
  }
  @Override
  protected void gwtSetUp() throws Exception {
    setRemoteCommunicationEnabled(false);
    InitVotes.setTimeoutMillis(60000);

    ClientSyncManager.resetInstance();

    // Unfortunately, GWTTestCase does not call our inherited module's onModuleLoad() methods
    // http://code.google.com/p/google-web-toolkit/issues/detail?id=3791
    new IOCBeanManagerLifecycle().resetBeanManager();
    new CDI().__resetSubsystem();
    new Container().onModuleLoad();
    new CDIClientBootstrap().onModuleLoad();

    InitVotes.startInitPolling();

    super.gwtSetUp();

    csm = IOC.getBeanManager().lookupBean(ClientSyncManager.class).getInstance();

    csm.getDesiredStateEm().removeAll();
    csm.getExpectedStateEm().removeAll();
  }
 @Override
 protected void gwtSetUp() throws Exception {
   super.gwtSetUp();
   app = IOC.getBeanManager().lookupBean(I18nTemplateTestApp.class).getInstance();
 }
 public static RenamePopupView getDefaultView() {
   return IOC.getBeanManager().lookupBean(RenamePopupView.class).getInstance();
 }
 @Override
 protected void gwtTearDown() throws Exception {
   Container.reset();
   IOC.reset();
   super.gwtTearDown();
 }
  @SuppressWarnings("unchecked")
  public void testDeclarativeSyncAndFieldValueChanges() {
    delayTestFinish(45000);

    final List<SyncResponse<SimpleEntity>> expectedSyncResponses =
        new ArrayList<SyncResponse<SimpleEntity>>();

    final Map<String, Object> parameters = new HashMap<String, Object>();

    // replace the caller so we can see what the SyncWorker asks its ClientSyncManager to do
    csm.dataSyncService =
        new Caller<DataSyncService>() {

          @Override
          public DataSyncService call(final RemoteCallback<?> callback) {
            return new DataSyncService() {

              @SuppressWarnings({"rawtypes"})
              @Override
              public <X> List<SyncResponse<X>> coldSync(
                  SyncableDataSet<X> dataSet, List<SyncRequestOperation<X>> actualClientRequests) {
                System.out.println("Short-circuiting DataSyncService call:");
                System.out.println("   dataSet = " + dataSet);
                System.out.println("   actualClientRequests = " + actualClientRequests);

                // Don't assert anything here! The timer we start later on will still fire if the
                // test
                // fails at this point!
                parameters.putAll(dataSet.getParameters());

                RemoteCallback rawRemoteCallback = callback;
                rawRemoteCallback.callback(expectedSyncResponses);

                return null; // this is the Caller stub. it doesn't return the value directly.
              }
            };
          }

          @Override
          public DataSyncService call(
              final RemoteCallback<?> callback, final ErrorCallback<?> errorCallback) {
            return call(callback);
          }

          @Override
          public DataSyncService call() {
            fail("Unexpected use of callback");
            return null; // NOTREACHED
          }
        };

    // Change the field values and fire IOC state change event so the sync worker can update its
    // query parameters
    syncBean = IOC.getBeanManager().lookupBean(DependentScopedSyncBean.class).getInstance();
    syncBean.setId(1337);
    syncBean.setName("changed");
    StateChange<DependentScopedSyncBean> changeEvent =
        IOC.getBeanManager().lookupBean(StateChange.class).getInstance();
    changeEvent.fireAsync(syncBean);

    new Timer() {

      @Override
      public void run() {
        assertEquals(1337l, parameters.get("id"));
        assertEquals("changed", parameters.get("string"));
        assertEquals("literalValue", parameters.get("literal"));

        // should get back the exact list of sync responses that we returned from our fake
        // Caller<DataSyncService> above
        assertNotNull(syncBean.getResponses());
        assertSame(expectedSyncResponses, syncBean.getResponses().getResponses());
        // we expect 2 sync tasks to have happened (one after a short delay in start() and the first
        // repeating one after 5s)
        assertEquals(2, syncBean.getCallbackCount());
        finishTest();
      }
    }.schedule(7000);
  }