/**
   * Will create a ServiceLocator after doing test-specific bindings from the TestModule
   *
   * @param name The name of the service locator to create. Should be unique per test, otherwise
   *     this method will fail.
   * @param parent The parent locator this one should have. May be null
   * @param modules The test modules, that will do test specific bindings. May be null
   * @return A service locator with all the test specific bindings bound
   */
  public static ServiceLocator create(
      String name, ServiceLocator parent, HK2TestModule... modules) {
    ServiceLocator retVal = factory.find(name);
    Assert.assertNull(
        "There is already a service locator of this name, change names to ensure a clean test: "
            + name,
        retVal);

    retVal = factory.create(name, parent);

    if (modules == null || modules.length <= 0) return retVal;

    DynamicConfigurationService dcs = retVal.getService(DynamicConfigurationService.class);
    Assert.assertNotNull("Their is no DynamicConfigurationService.  Epic fail", dcs);

    DynamicConfiguration dc = dcs.createDynamicConfiguration();
    Assert.assertNotNull("DynamicConfiguration creation failure", dc);

    for (HK2TestModule module : modules) {
      module.configure(dc);
    }

    dc.commit();

    return retVal;
  }
  /**
   * Registers HK2 binders into the HK2 service register.
   *
   * @param binders binders to be registered.
   */
  public void registerAdditionalBinders(final Iterable<Binder> binders) {
    final DynamicConfiguration dc = Injections.getConfiguration(locator);

    for (Binder binder : binders) {
      binder.bind(dc);
    }
    dc.commit();
  }
Exemple #3
0
  private static void bind(ServiceLocator locator, Binder binder) {
    DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class);
    DynamicConfiguration dc = dcs.createDynamicConfiguration();

    locator.inject(binder);
    binder.bind(dc);

    dc.commit();
  }
Exemple #4
0
  /* package */ @SuppressWarnings({"unchecked"})
  void register() {
    ServiceLocator locator = getServiceLocator();

    ActiveDescriptor<?> myselfReified = locator.reifyDescriptor(this);

    DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class);
    DynamicConfiguration dc = dcs.createDynamicConfiguration();

    //        habitat.add(this);
    HK2Loader loader = this.model.classLoaderHolder;

    Set<Type> ctrs = new HashSet<Type>();
    ctrs.add(myselfReified.getImplementationClass());

    if (ConfigBean.class.isAssignableFrom(this.getClass())) {
      ctrs.add(ConfigBean.class);
    }

    DomDescriptor<Dom> domDesc =
        new DomDescriptor<Dom>(
            this, ctrs, Singleton.class, getImplementation(), new HashSet<Annotation>());
    domDesc.setLoader(loader);
    domDescriptor = dc.addActiveDescriptor(domDesc, false);

    String key = getKey();
    for (String contract : model.contracts) {
      ActiveDescriptor<Dom> alias = new AliasDescriptor<Dom>(locator, domDescriptor, contract, key);
      dc.addActiveDescriptor(alias, false);
    }
    if (key != null) {
      ActiveDescriptor<Dom> alias =
          new AliasDescriptor<Dom>(locator, domDescriptor, model.targetTypeName, key);
      dc.addActiveDescriptor(alias, false);
    }

    dc.commit();

    serviceHandle = getHabitat().getServiceHandle(domDescriptor);
  }
  @Override
  public boolean bind(Class<?> component, Set<Class<?>> providerContracts) {
    if (injector != null) {
      Key<?> key = Key.get(component);
      Binding<?> binding = injector.getExistingBinding(key);

      // Does the constructor require Guice Binding?
      if (binding == null) {
        binding = injector.getBinding(key);
      }

      DynamicConfiguration c = Injections.getConfiguration(locator);
      ServiceBindingBuilder bb =
          Injections.newFactoryBinder(new GuiceBindingComponentFactory(binding));
      bb.to(component);
      Injections.addBinding(bb, c);
      c.commit();
      return true;
    }

    return false;
  }
  @SuppressWarnings({"unchecked", "rawtypes"})
  public Task<Void> start() {

    // Ensuring that jersey will use singletons from the orbit container.
    ServiceLocator locator = Injections.createLocator();
    DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class);
    DynamicConfiguration dc = dcs.createDynamicConfiguration();

    final List<Class<?>> classes = new ArrayList<>(providers);
    if (container != null) {
      classes.addAll(container.getClasses());
      for (final Class<?> c : container.getClasses()) {
        if (c.isAnnotationPresent(Singleton.class)) {
          Injections.addBinding(
              Injections.newFactoryBinder(
                      new Factory() {
                        @Override
                        public Object provide() {
                          return container.get(c);
                        }

                        @Override
                        public void dispose(final Object instance) {}
                      })
                  .to(c),
              dc);
        }
      }
    }
    dc.commit();

    final ResourceConfig resourceConfig = new ResourceConfig();

    // installing jax-rs classes known by the orbit container.
    for (final Class c : classes) {
      if (c.isAnnotationPresent(javax.ws.rs.Path.class)
          || c.isAnnotationPresent(javax.ws.rs.ext.Provider.class)) {
        resourceConfig.register(c);
      }
    }

    final WebAppContext webAppContext = new WebAppContext();
    final ProtectionDomain protectionDomain = EmbeddedHttpServer.class.getProtectionDomain();
    final URL location = protectionDomain.getCodeSource().getLocation();
    logger.info(location.toExternalForm());
    webAppContext.setInitParameter("useFileMappedBuffer", "false");
    webAppContext.setWar(location.toExternalForm());
    // this sets the default service locator to one that bridges to the orbit container.
    webAppContext.getServletContext().setAttribute(ServletProperties.SERVICE_LOCATOR, locator);
    webAppContext.setContextPath("/*");
    webAppContext.addServlet(new ServletHolder(new ServletContainer(resourceConfig)), "/*");

    final ContextHandler resourceContext = new ContextHandler();
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setWelcomeFiles(new String[] {"index.html"});
    resourceHandler.setBaseResource(Resource.newClassPathResource("/web"));

    resourceContext.setHandler(resourceHandler);
    resourceContext.setInitParameter("useFileMappedBuffer", "false");
    final ContextHandlerCollection contexts = new ContextHandlerCollection();

    contexts.setHandlers(
        new Handler[] {
          wrapHandlerWithMetrics(resourceContext, "resourceContext"),
          wrapHandlerWithMetrics(webAppContext, "webAppContext")
        });

    server = new Server(port);
    server.setHandler(contexts);
    try {
      /// Initialize javax.websocket layer
      final ServerContainer serverContainer =
          WebSocketServerContainerInitializer.configureContext(webAppContext);

      for (Class c : classes) {
        if (c.isAnnotationPresent(ServerEndpoint.class)) {
          final ServerEndpoint annotation = (ServerEndpoint) c.getAnnotation(ServerEndpoint.class);

          final ServerEndpointConfig serverEndpointConfig =
              ServerEndpointConfig.Builder.create(c, annotation.value())
                  .configurator(
                      new ServerEndpointConfig.Configurator() {
                        @Override
                        public <T> T getEndpointInstance(final Class<T> endpointClass)
                            throws InstantiationException {
                          return container.get(endpointClass);
                        }
                      })
                  .build();

          serverContainer.addEndpoint(serverEndpointConfig);
        }
      }
    } catch (Exception e) {
      logger.error("Error starting jetty", e);
      throw new UncheckedException(e);
    }

    try {
      server.start();
    } catch (Exception e) {
      logger.error("Error starting jetty", e);
      throw new UncheckedException(e);
    }
    return Task.done();
  }
  private void bindProvidersAndResources(
      final Set<ComponentProvider> componentProviders,
      final ComponentBag componentBag,
      final Set<Class<?>> resourceClasses,
      final Set<Object> resourceInstances) {

    final JerseyResourceContext resourceContext = locator.getService(JerseyResourceContext.class);
    final DynamicConfiguration dc = Injections.getConfiguration(locator);
    final Set<Class<?>> registeredClasses = runtimeConfig.getRegisteredClasses();

    // Merge programmatic resource classes with component classes.
    Set<Class<?>> classes = Sets.newIdentityHashSet();
    classes.addAll(
        Sets.filter(
            componentBag.getClasses(ComponentBag.EXCLUDE_META_PROVIDERS),
            new Predicate<Class<?>>() {
              @Override
              public boolean apply(Class<?> componentClass) {
                return Providers.checkProviderRuntime(
                    componentClass,
                    componentBag.getModel(componentClass),
                    RuntimeType.SERVER,
                    !registeredClasses.contains(componentClass),
                    resourceClasses.contains(componentClass));
              }
            }));
    classes.addAll(resourceClasses);

    // Bind classes.
    for (Class<?> componentClass : classes) {
      ContractProvider model = componentBag.getModel(componentClass);
      if (resourceClasses.contains(componentClass)) {
        if (bindWithComponentProvider(componentClass, model, componentProviders)) {
          continue;
        }

        if (!Resource.isAcceptable(componentClass)) {
          LOGGER.warning(LocalizationMessages.NON_INSTANTIABLE_COMPONENT(componentClass));
          continue;
        }

        if (model != null
            && !Providers.checkProviderRuntime(
                componentClass,
                model,
                RuntimeType.SERVER,
                !registeredClasses.contains(componentClass),
                true)) {
          model = null;
        }
        resourceContext.unsafeBindResource(componentClass, model, dc);
      } else {
        ProviderBinder.bindProvider(componentClass, model, dc);
      }
    }

    // Merge programmatic resource instances with other component instances.
    Set<Object> instances = Sets.newHashSet();
    instances.addAll(
        Sets.filter(
            componentBag.getInstances(ComponentBag.EXCLUDE_META_PROVIDERS),
            new Predicate<Object>() {
              @Override
              public boolean apply(Object component) {
                final Class<?> componentClass = component.getClass();
                return Providers.checkProviderRuntime(
                    componentClass,
                    componentBag.getModel(componentClass),
                    RuntimeType.SERVER,
                    !registeredClasses.contains(componentClass),
                    resourceInstances.contains(component));
              }
            }));
    instances.addAll(resourceInstances);

    // Bind instances.
    for (Object component : instances) {
      ContractProvider model = componentBag.getModel(component.getClass());
      if (resourceInstances.contains(component)) {
        if (model != null
            && !Providers.checkProviderRuntime(
                component.getClass(),
                model,
                RuntimeType.SERVER,
                !registeredClasses.contains(component.getClass()),
                true)) {
          model = null;
        }
        resourceContext.unsafeBindResource(component, model, dc);
      } else {
        ProviderBinder.bindProvider(component, model, dc);
      }
    }

    dc.commit();
  }
Exemple #8
0
  private <T> XmlRootHandle<T> unmarshallClass(
      URI uri,
      ModelImpl model,
      XmlServiceParser localParser,
      XMLStreamReader reader,
      boolean advertise,
      boolean advertiseInHub)
      throws Exception {
    long elapsedUpToJAXB = 0;
    if (JAUtilities.DEBUG_GENERATION_TIMING) {
      elapsedUpToJAXB = System.currentTimeMillis();
    }

    Hk2JAXBUnmarshallerListener listener =
        new Hk2JAXBUnmarshallerListener(jaUtilities, classReflectionHelper);

    long jaxbUnmarshallElapsedTime = 0L;
    if (JAUtilities.DEBUG_GENERATION_TIMING) {
      jaxbUnmarshallElapsedTime = System.currentTimeMillis();
      elapsedUpToJAXB = jaxbUnmarshallElapsedTime - elapsedUpToJAXB;
      Logger.getLogger()
          .debug("Time up to parsing " + uri + " is " + elapsedUpToJAXB + " milliseconds");
    }

    T root;
    if (localParser != null) {
      root = localParser.parseRoot(model, uri, listener);
    } else {
      root = XmlStreamImpl.parseRoot(this, model, reader, listener);
    }

    long elapsedJAXBToAdvertisement = 0;
    if (JAUtilities.DEBUG_GENERATION_TIMING) {
      elapsedJAXBToAdvertisement = System.currentTimeMillis();
      jaxbUnmarshallElapsedTime = elapsedJAXBToAdvertisement - jaxbUnmarshallElapsedTime;
      Logger.getLogger()
          .debug(
              "Time parsing "
                  + uri
                  + " is "
                  + jaxbUnmarshallElapsedTime
                  + " milliseconds "
                  + ", now with "
                  + jaUtilities.getNumGenerated()
                  + " proxies generated and "
                  + jaUtilities.getNumPreGenerated()
                  + " pre generated proxies loaded");
    }

    DynamicChangeInfo changeControl =
        new DynamicChangeInfo(
            jaUtilities,
            ((advertiseInHub) ? hub : null),
            this,
            ((advertise) ? dynamicConfigurationService : null),
            serviceLocator);

    for (BaseHK2JAXBBean base : listener.getAllBeans()) {
      String instanceName = Utilities.createInstanceName(base);
      base._setInstanceName(instanceName);

      base._setDynamicChangeInfo(changeControl);

      if (DEBUG_PARSING) {
        Logger.getLogger().debug("XmlServiceDebug found bean " + base);
      }
    }
    if (DEBUG_PARSING) {
      Logger.getLogger().debug("XmlServiceDebug after parsing all beans in " + uri);
    }

    long elapsedPreAdvertisement = 0L;
    if (JAUtilities.DEBUG_GENERATION_TIMING) {
      elapsedPreAdvertisement = System.currentTimeMillis();
      elapsedJAXBToAdvertisement = elapsedPreAdvertisement - elapsedJAXBToAdvertisement;
      Logger.getLogger()
          .debug(
              "Time from parsing to PreAdvertisement "
                  + uri
                  + " is "
                  + elapsedJAXBToAdvertisement
                  + " milliseconds");
    }

    DynamicConfiguration config =
        (advertise) ? dynamicConfigurationService.createDynamicConfiguration() : null;
    WriteableBeanDatabase wdb = (advertiseInHub) ? hub.getWriteableDatabaseCopy() : null;

    LinkedList<BaseHK2JAXBBean> allBeans = listener.getAllBeans();
    List<ActiveDescriptor<?>> addedDescriptors =
        new ArrayList<ActiveDescriptor<?>>(allBeans.size());
    for (BaseHK2JAXBBean bean : allBeans) {
      ActiveDescriptor<?> added = Utilities.advertise(wdb, config, bean);
      if (added != null) {
        addedDescriptors.add(added);
      }
    }

    long elapsedHK2Advertisement = 0L;
    if (JAUtilities.DEBUG_GENERATION_TIMING) {
      elapsedHK2Advertisement = System.currentTimeMillis();
      elapsedPreAdvertisement = elapsedHK2Advertisement - elapsedPreAdvertisement;
      Logger.getLogger()
          .debug(
              "Time from JAXB to PreAdvertisement "
                  + uri
                  + " is "
                  + elapsedPreAdvertisement
                  + " milliseconds");
    }

    if (config != null) {
      config.commit();
    }

    long elapsedHubAdvertisement = 0L;
    if (JAUtilities.DEBUG_GENERATION_TIMING) {
      elapsedHubAdvertisement = System.currentTimeMillis();
      elapsedHK2Advertisement = elapsedHubAdvertisement - elapsedHK2Advertisement;
      Logger.getLogger()
          .debug(
              "Time to advertise "
                  + uri
                  + " in HK2 is "
                  + elapsedHK2Advertisement
                  + " milliseconds");
    }

    if (wdb != null) {
      wdb.commit(new XmlHubCommitMessage() {});
    }

    // The following is put here so that InstanceLifecycleListeners will get invoked at this time
    // rather than later so that defaulting can be done now.  It doesn't hurt because these are
    // all constant descriptors
    for (ActiveDescriptor<?> ad : addedDescriptors) {
      serviceLocator.getServiceHandle(ad).getService();
    }

    if (JAUtilities.DEBUG_GENERATION_TIMING) {
      elapsedHubAdvertisement = System.currentTimeMillis() - elapsedHubAdvertisement;
      Logger.getLogger()
          .debug(
              "Time to advertise "
                  + uri
                  + " in Hub is "
                  + elapsedHubAdvertisement
                  + " milliseconds");
    }

    return new XmlRootHandleImpl<T>(
        this, hub, root, model, uri, advertise, advertiseInHub, changeControl);
  }