@Test
  public void testExtraDependencies() throws InvocationTargetException, InstantiationException {
    IEclipseContext context = EclipseContextFactory.create();
    context.set("arg1", "abc");
    context.set("arg2", Integer.valueOf(123));

    IEclipseContext otherContext = EclipseContextFactory.create();
    otherContext.set("arg3", "other");

    context.set("otherContext", otherContext);

    TestObject object = ContextInjectionFactory.make(TestObject.class, context);

    // check that initial values are properly injected
    assertEquals("abc", object.string);
    assertEquals(Integer.valueOf(123), object.integer);
    assertEquals("other", object.other);

    // modify argument value to cause update - bug 308650
    context.set("arg2", Integer.valueOf(789));

    // change the "other" value; should not be propagated
    otherContext.set("arg3", "wrong");
    assertEquals("other", object.other);

    // dispose the other context; should not cause disposal of the test object
    otherContext.dispose();
    assertEquals("other", object.other);
    assertFalse(object.disposed);

    // remove "other" context, should not be propagated
    context.remove("otherContext");
    assertEquals("other", object.other);

    // check that changes in the method arguments are propagated
    context.set("arg1", "xyz");
    context.set("arg2", Integer.valueOf(456));
    assertEquals("xyz", object.string);
    assertEquals(Integer.valueOf(456), object.integer);
    assertNull(object.other);

    // check that disposal of the injected context causes disposal of the injected object
    context.dispose();
    assertTrue(object.disposed);
    assertNotNull(object.string);
    assertNotNull(object.integer);
    assertNull(object.other);
  }
  @Test
  public void testInjectWildCard() {
    IEclipseContext context = EclipseContextFactory.create();
    final Display d = Display.getDefault();

    context.set(Realm.class, DisplayRealm.getRealm(d));
    context.set(
        UISynchronize.class,
        new UISynchronize() {

          @Override
          public void syncExec(Runnable runnable) {
            d.syncExec(runnable);
          }

          @Override
          public void asyncExec(Runnable runnable) {
            d.asyncExec(runnable);
          }
        });

    InjectStarEvent target = ContextInjectionFactory.make(InjectStarEvent.class, context);

    // initial state
    assertEquals(0, target.counter1);
    assertNull(target.data);

    // send event
    helper.sendEvent("e4/test/eventInjection", "sample");

    assertEquals(1, target.counter1);
    assertEquals("sample", target.data);
  }
 /*
  * (non-Javadoc)
  *
  * @seeorg.eclipse.e4.core.commands.EHandlerService#executeHandler(org.eclipse.core.commands.
  * ParameterizedCommand)
  */
 public Object executeHandler(ParameterizedCommand command) {
   final IEclipseContext staticContext = EclipseContextFactory.create(TMP_STATIC_CONTEXT);
   try {
     return executeHandler(command, staticContext);
   } finally {
     staticContext.dispose();
   }
 }
 public boolean canExecute(ParameterizedCommand command) {
   final IEclipseContext staticContext = EclipseContextFactory.create(TMP_STATIC_CONTEXT);
   try {
     return canExecute(command, staticContext);
   } finally {
     staticContext.dispose();
   }
 }
 private void wrapSetup() {
   IEclipseContext context = EclipseContextFactory.create();
   InjectTarget target = ContextInjectionFactory.make(InjectTarget.class, context);
   // send event
   helper.sendEvent("e4/test/event1", "event1data");
   assertEquals(1, target.counter1);
   assertEquals("event1data", target.string1);
   target.valid = false;
 }
  /** Tests the Registration of an Event Hanlder in the event broker of the eclpse context. */
  @Test
  public void testEventBrokerEventHanlderRegistration() {
    TestProtocolService protocolService = new TestProtocolService();
    IEclipseContext context = EclipseContextFactory.create();
    final Map<String, EventHandler> topics = new HashMap<String, EventHandler>();
    context.set(
        IEventBroker.class,
        new IEventBroker() {

          @Override
          public boolean send(String topic, Object data) {
            return false;
          }

          @Override
          public boolean post(String topic, Object data) {
            return false;
          }

          @Override
          public boolean subscribe(String topic, EventHandler eventHandler) {
            topics.put(topic, eventHandler);
            return true;
          }

          @Override
          public boolean subscribe(
              String topic, String filter, EventHandler eventHandler, boolean headless) {
            return false;
          }

          @Override
          public boolean unsubscribe(EventHandler eventHandler) {
            return false;
          }
        });
    protocolService.compute(context, null);
    EventHandler handler =
        topics.get(TestEditorCoreEventConstants.TESTSTRUCTURE_MODEL_CHANGED_DELETED);
    assertNotNull("Hanlder should be registered", handler);
    TestCase testCase = new TestCase();
    testCase.setName("TestCase1");
    protocolService.set(testCase, new TestResult());
    assertNotNull(protocolService.get(testCase));
    Map<String, String> properties = new HashMap<String, String>();
    properties.put("org.eclipse.e4.data", testCase.getFullName());
    Event event =
        new Event(TestEditorCoreEventConstants.TESTSTRUCTURE_MODEL_CHANGED_DELETED, properties);
    handler.handleEvent(event);
    assertNull(protocolService.get(testCase));
  }
 private IEclipseContext getStaticContext() {
   if (infoContext == null) {
     IEclipseContext parentContext = renderer.getContext(toolbarModel);
     if (parentContext != null) {
       infoContext = parentContext.createChild(STATIC_CONTEXT);
     } else {
       infoContext = EclipseContextFactory.create(STATIC_CONTEXT);
     }
     ContributionsAnalyzer.populateModelInterfaces(
         toolbarModel, infoContext, toolbarModel.getClass().getInterfaces());
     infoContext.set(ToolBarRenderer.class, renderer);
   }
   return infoContext;
 }
  @Test
  public void testV() throws Exception {
    IEclipseContext parentContext = EclipseContextFactory.create();
    parentContext.set("aString", "");
    IEclipseContext context = parentContext.createChild();

    MyTest test = ContextInjectionFactory.make(MyTest.class, context);

    assertEquals(0, test.getCount());
    context.dispose();
    assertEquals("Context disposed, @PreDestroy should've been called", 1, test.getCount());
    parentContext.dispose();
    assertEquals(
        "Parent context disposed, @PreDestroy should not have been called again",
        1,
        test.getCount());
  }
  private void setEnabled(MHandledMenuItem itemModel, MenuItem newItem) {
    ParameterizedCommand cmd = itemModel.getWbCommand();
    if (cmd == null) {
      return;
    }
    final IEclipseContext lclContext = getContext(itemModel);
    EHandlerService service = lclContext.get(EHandlerService.class);
    final IEclipseContext staticContext = EclipseContextFactory.create(HMI_STATIC_CONTEXT);
    ContributionsAnalyzer.populateModelInterfaces(
        itemModel, staticContext, itemModel.getClass().getInterfaces());

    try {
      itemModel.setEnabled(service.canExecute(cmd, staticContext));
    } finally {
      staticContext.dispose();
    }
    newItem.setEnabled(itemModel.isEnabled());
  }
Ejemplo n.º 10
0
  @Override
  public boolean load() {
    if (sessionService == null) {
      // we abort
      logger.info("Aborting catalog " + params.getName() + " loading : session is not set yet");
      return false;
    }
    Session session = sessionService.getSession();
    logger.info(
        "[PadreCatalog] Session service instanciated. Session username is "
            + sessionService.getSession().getUsername());
    this.layertreeAsJsonNode = getLayertree();

    // if null, then it failed. We exit the function.
    if (this.layertreeAsJsonNode == null) {
      logger.error("ERROR parsing layertree (" + this.getClass().getName() + ")");
      return false;
    }

    // create a new local_ context
    IEclipseContext catalogContext = EclipseContextFactory.create();
    catalogState = new PadreCatalogState();
    catalogContext.set(PadreCatalogState.class, catalogState);

    // connect new local context with context hierarchy
    catalogContext.setParent(context);

    this.rootNode = ContextInjectionFactory.make(FolderNode.class, catalogContext);
    // this.rootNode = new FolderNode();
    this.rootNode.setName(params.getName());
    this.catalogState.addExpandedNode(this.rootNode);
    this.rootNode.loadFromJson(this.layertreeAsJsonNode);

    this.checkInitialNodes(this.catalogState.getCheckedNodes());

    return true;
  }
  @Test
  public void testEventInjection() {
    IInjector injector = InjectorFactory.getDefault();
    injector.addBinding(MyBinding.class);

    IEclipseContext context = EclipseContextFactory.create();
    final Display d = Display.getDefault();

    context.set(Realm.class, DisplayRealm.getRealm(d));
    context.set(
        UISynchronize.class,
        new UISynchronize() {

          @Override
          public void syncExec(Runnable runnable) {
            d.syncExec(runnable);
          }

          @Override
          public void asyncExec(Runnable runnable) {
            d.asyncExec(runnable);
          }
        });
    ContextInjectionFactory.setDefault(context);
    InjectTarget target = ContextInjectionFactory.make(InjectTarget.class, context);

    // initial state
    assertEquals(0, target.counter1);
    assertNull(target.string1);
    assertEquals(0, target.counter2);
    assertNull(target.string2);
    assertEquals(1, target.counter3);
    assertNull(target.string3);
    assertNotNull(target.myBinding);

    // send event1
    helper.sendEvent("e4/test/event1", "event1data");

    assertEquals(1, target.counter1);
    assertEquals("event1data", target.string1);
    assertEquals(0, target.counter2);
    assertNull(target.string2);
    assertEquals(1, target.counter3);
    assertNull(target.string3);
    assertNotNull(target.myBinding);

    // send event2
    helper.sendEvent("e4/test/event2", "event2data");

    assertEquals(1, target.counter1);
    assertEquals("event1data", target.string1);
    assertEquals(1, target.counter2);
    assertEquals("event2data", target.string2);
    assertEquals(1, target.counter3);
    assertNull(target.string3);
    assertNotNull(target.myBinding);

    // send event3
    helper.sendEvent("e4/test/event3", "event3data");

    assertEquals(1, target.counter1);
    assertEquals("event1data", target.string1);
    assertEquals(1, target.counter2);
    assertEquals("event2data", target.string2);
    assertEquals(2, target.counter3);
    assertEquals("event3data", target.string3);
    assertNotNull(target.myBinding);

    // send event1 again
    helper.sendEvent("e4/test/event1", "abc");

    assertEquals(2, target.counter1);
    assertEquals("abc", target.string1);
    assertEquals(1, target.counter2);
    assertEquals("event2data", target.string2);
    assertEquals(2, target.counter3);
    assertEquals("event3data", target.string3);
    assertNotNull(target.myBinding);
  }
Ejemplo n.º 12
0
  public E4Workbench createE4Workbench(
      IApplicationContext applicationContext, final Display display) {
    args = (String[]) applicationContext.getArguments().get(IApplicationContext.APPLICATION_ARGS);

    IEclipseContext appContext = createDefaultContext();
    appContext.set(Display.class, display);
    appContext.set(Realm.class, DisplayRealm.getRealm(display));
    appContext.set(
        UISynchronize.class,
        new UISynchronize() {

          @Override
          public void syncExec(Runnable runnable) {
            if (display != null && !display.isDisposed()) {
              display.syncExec(runnable);
            }
          }

          @Override
          public void asyncExec(Runnable runnable) {
            if (display != null && !display.isDisposed()) {
              display.asyncExec(runnable);
            }
          }
        });
    appContext.set(IApplicationContext.class, applicationContext);

    // This context will be used by the injector for its
    // extended data suppliers
    ContextInjectionFactory.setDefault(appContext);

    // Get the factory to create DI instances with
    IContributionFactory factory = appContext.get(IContributionFactory.class);

    // Install the life-cycle manager for this session if there's one
    // defined
    Optional<String> lifeCycleURI =
        getArgValue(IWorkbench.LIFE_CYCLE_URI_ARG, applicationContext, false);
    lifeCycleURI.ifPresent(
        lifeCycleURIValue -> {
          lcManager = factory.create(lifeCycleURIValue, appContext);
          if (lcManager != null) {
            // Let the manager manipulate the appContext if desired
            ContextInjectionFactory.invoke(lcManager, PostContextCreate.class, appContext, null);
          }
        });

    Optional<String> forcedPerspectiveId =
        getArgValue(PERSPECTIVE_ARG_NAME, applicationContext, false);
    forcedPerspectiveId.ifPresent(
        forcedPerspectiveIdValue ->
            appContext.set(E4Workbench.FORCED_PERSPECTIVE_ID, forcedPerspectiveIdValue));

    String showLocation = getLocationFromCommandLine();
    if (showLocation != null) {
      appContext.set(E4Workbench.FORCED_SHOW_LOCATION, showLocation);
    }

    // Create the app model and its context
    MApplication appModel = loadApplicationModel(applicationContext, appContext);
    appModel.setContext(appContext);

    boolean isRtl = ((Window.getDefaultOrientation() & SWT.RIGHT_TO_LEFT) != 0);
    appModel.getTransientData().put(E4Workbench.RTL_MODE, isRtl);

    // for compatibility layer: set the application in the OSGi service
    // context (see Workbench#getInstance())
    if (!E4Workbench.getServiceContext().containsKey(MApplication.class)) {
      // first one wins.
      E4Workbench.getServiceContext().set(MApplication.class, appModel);
    }

    // Set the app's context after adding itself
    appContext.set(MApplication.class, appModel);

    // adds basic services to the contexts
    initializeServices(appModel);

    // let the life cycle manager add to the model
    if (lcManager != null) {
      ContextInjectionFactory.invoke(lcManager, ProcessAdditions.class, appContext, null);
      ContextInjectionFactory.invoke(lcManager, ProcessRemovals.class, appContext, null);
    }

    // Create the addons
    IEclipseContext addonStaticContext = EclipseContextFactory.create();
    for (MAddon addon : appModel.getAddons()) {
      addonStaticContext.set(MAddon.class, addon);
      Object obj = factory.create(addon.getContributionURI(), appContext, addonStaticContext);
      addon.setObject(obj);
    }

    // Parse out parameters from both the command line and/or the product
    // definition (if any) and put them in the context
    Optional<String> xmiURI = getArgValue(IWorkbench.XMI_URI_ARG, applicationContext, false);
    xmiURI.ifPresent(
        xmiURIValue -> {
          appContext.set(IWorkbench.XMI_URI_ARG, xmiURIValue);
        });

    setCSSContextVariables(applicationContext, appContext);

    Optional<String> rendererFactoryURI =
        getArgValue(E4Workbench.RENDERER_FACTORY_URI, applicationContext, false);
    rendererFactoryURI.ifPresent(
        rendererFactoryURIValue -> {
          appContext.set(E4Workbench.RENDERER_FACTORY_URI, rendererFactoryURIValue);
        });

    // This is a default arg, if missing we use the default rendering engine
    Optional<String> presentationURI =
        getArgValue(IWorkbench.PRESENTATION_URI_ARG, applicationContext, false);
    appContext.set(
        IWorkbench.PRESENTATION_URI_ARG, presentationURI.orElse(PartRenderingEngine.engineURI));

    // Instantiate the Workbench (which is responsible for
    // 'running' the UI (if any)...
    return workbench = new E4Workbench(appModel, appContext);
  }
  public static void initializeStyling(Display display, IEclipseContext appContext) {
    String cssTheme = (String) appContext.get(E4Application.THEME_ID);
    String cssURI = (String) appContext.get(E4Workbench.CSS_URI_ARG);

    if (cssTheme != null) {
      String cssResourcesURI = (String) appContext.get(E4Workbench.CSS_RESOURCE_URI_ARG);

      Bundle bundle = WorkbenchSWTActivator.getDefault().getBundle();
      BundleContext context = bundle.getBundleContext();
      ServiceReference ref = context.getServiceReference(IThemeManager.class.getName());
      IThemeManager mgr = (IThemeManager) context.getService(ref);
      final IThemeEngine engine = mgr.getEngineForDisplay(display);

      // Store the app context
      IContributionFactory contribution =
          (IContributionFactory) appContext.get(IContributionFactory.class.getName());
      IEclipseContext cssContext = EclipseContextFactory.create();
      cssContext.set(IContributionFactory.class.getName(), contribution);
      display.setData("org.eclipse.e4.ui.css.context", cssContext); // $NON-NLS-1$

      // Create the OSGi resource locator
      if (cssResourcesURI != null) {
        // TODO: Should this be set through an extension as well?
        engine.registerResourceLocator(new OSGiResourceLocator(cssResourcesURI));
      }

      engine.restore(cssTheme);
      // TODO Should we create an empty default theme?

      appContext.set(IThemeEngine.class.getName(), engine);

      appContext.set(
          IStylingEngine.SERVICE_NAME,
          new IStylingEngine() {
            public void setClassname(Object widget, String classname) {
              WidgetElement.setCSSClass((Widget) widget, classname);
              engine.applyStyles((Widget) widget, true);
            }

            public void setId(Object widget, String id) {
              WidgetElement.setID((Widget) widget, id);
              engine.applyStyles((Widget) widget, true);
            }

            public void style(Object widget) {
              engine.applyStyles((Widget) widget, true);
            }

            public CSSStyleDeclaration getStyle(Object widget) {
              return engine.getStyle((Widget) widget);
            }

            public void setClassnameAndId(Object widget, String classname, String id) {
              WidgetElement.setCSSClass((Widget) widget, classname);
              WidgetElement.setID((Widget) widget, id);
              engine.applyStyles((Widget) widget, true);
            }
          });
    } else if (cssURI != null) {
      String cssResourcesURI = (String) appContext.get(E4Workbench.CSS_RESOURCE_URI_ARG);
      final CSSSWTEngineImpl engine = new CSSSWTEngineImpl(display, true);
      WidgetElement.setEngine(display, engine);
      if (cssResourcesURI != null) {
        engine
            .getResourcesLocatorManager()
            .registerResourceLocator(new OSGiResourceLocator(cssResourcesURI.toString()));
      }
      // FIXME: is this needed?
      display.setData("org.eclipse.e4.ui.css.context", appContext); // $NON-NLS-1$
      appContext.set(
          IStylingEngine.SERVICE_NAME,
          new IStylingEngine() {
            public void setClassname(Object widget, String classname) {
              WidgetElement.setCSSClass((Widget) widget, classname);
              engine.applyStyles((Widget) widget, true);
            }

            public void setId(Object widget, String id) {
              WidgetElement.setID((Widget) widget, id);
              engine.applyStyles((Widget) widget, true);
            }

            public void style(Object widget) {
              engine.applyStyles((Widget) widget, true);
            }

            public CSSStyleDeclaration getStyle(Object widget) {
              Element e = engine.getCSSElementContext(widget).getElement();
              if (e == null) {
                return null;
              }
              return engine.getViewCSS().getComputedStyle(e, null);
            }

            public void setClassnameAndId(Object widget, String classname, String id) {
              WidgetElement.setCSSClass((Widget) widget, classname);
              WidgetElement.setID((Widget) widget, id);
              engine.applyStyles((Widget) widget, true);
            }
          });

      URL url;
      InputStream stream = null;
      try {
        url = FileLocator.resolve(new URL(cssURI));
        stream = url.openStream();
        engine.parseStyleSheet(stream);
      } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } finally {
        if (stream != null) {
          try {
            stream.close();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
      }

      Shell[] shells = display.getShells();
      for (Shell s : shells) {
        try {
          s.setRedraw(false);
          s.reskin(SWT.ALL);
          engine.applyStyles(s, true);
        } catch (Exception e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } finally {
          s.setRedraw(true);
        }
      }
    }

    CSSRenderingUtils cssUtils = ContextInjectionFactory.make(CSSRenderingUtils.class, appContext);
    appContext.set(CSSRenderingUtils.class, cssUtils);
  }