public ModelController createController(final ModelNode model, final Setup registration)
      throws InterruptedException {
    final ServiceController<?> existingController =
        serviceContainer.getService(ServiceName.of("ModelController"));
    if (existingController != null) {
      final CountDownLatch latch = new CountDownLatch(1);
      existingController.addListener(
          new AbstractServiceListener<Object>() {
            public void listenerAdded(ServiceController<?> serviceController) {
              serviceController.setMode(ServiceController.Mode.REMOVE);
            }

            public void transition(
                ServiceController<?> serviceController, ServiceController.Transition transition) {
              if (transition.equals(ServiceController.Transition.REMOVING_to_REMOVED)) {
                latch.countDown();
              }
            }
          });
      latch.await();
    }

    ServiceTarget target = serviceContainer.subTarget();
    ControlledProcessState processState = new ControlledProcessState(true);
    ModelControllerService svc = new ModelControllerService(processState, registration, model);
    ServiceBuilder<ModelController> builder =
        target.addService(ServiceName.of("ModelController"), svc);
    builder.install();
    svc.latch.await();
    ModelController controller = svc.getValue();
    ModelNode setup = Util.getEmptyOperation("setup", new ModelNode());
    controller.execute(setup, null, null, null);
    processState.setRunning();
    return controller;
  }
  public static void main(String[] args) throws Exception {
    final int totalServiceDefinitions = Integer.parseInt(args[0]);
    final int threadPoolSize = Integer.parseInt(args[1]);

    final ServiceContainer container = ServiceContainer.Factory.create();
    final ThreadPoolExecutor executor =
        new ThreadPoolExecutor(
            threadPoolSize,
            threadPoolSize,
            1000,
            TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>());
    container.setExecutor(executor);

    BatchBuilder batch = container.batchBuilder();

    final LatchedFinishListener listener = new LatchedFinishListener();

    final Value<Field> testFieldValue =
        new CachedValue<Field>(
            new LookupFieldValue(new ImmediateValue<Class<?>>(TestObject.class), "test"));

    final List<Value<Class<?>>> params =
        Collections.singletonList((Value<Class<?>>) new ImmediateValue<Class<?>>(TestObject.class));
    final List<Value<Method>> setterMethodValues = new ArrayList<Value<Method>>(5);
    for (int i = 0; i < 5; i++)
      setterMethodValues.add(
          new CachedValue<Method>(
              new LookupMethodValue(
                  new ImmediateValue<Class<?>>(TestObject.class), "setOther" + (i), params)));

    for (int i = 0; i < totalServiceDefinitions; i++) {
      final TestObject testObject = new TestObject("test" + i);
      final TestObjectService service = new TestObjectService(testObject);
      final ServiceBuilder<TestObject> builder =
          batch.addService(ServiceName.of(("test" + i).intern()), service).addListener(listener);

      final Object injectedValue = new Object();
      //            builder.addInjection(injectedValue).toFieldValue(testFieldValue);

      int nextDivByFive = (5 - (i % 5)) + i;
      int numDeps = Math.min(nextDivByFive - i, totalServiceDefinitions - i - 1);
      for (int j = 0; j < numDeps; j++) {
        int depId = i + j + 1;
        if (depId % 5 == 0) continue;

        //                builder.addDependency(ServiceName.of(("test" +
        // depId).intern())).toMethodValue(setterMethodValues.get(j),
        // Collections.singletonList(Values.injectedValue()));
      }
    }

    batch.install();
    listener.await();
    System.out.println(totalServiceDefinitions + " : " + listener.getElapsedTime() / 1000.0);
    container.shutdown();
    executor.shutdown();
  }
Ejemplo n.º 3
0
  /**
   * Create a new controller with the passed in operations.
   *
   * @param additionalInit Additional initialization that should be done to the parsers, controller
   *     and service container before initializing our extension
   * @param bootOperations the operations
   */
  protected KernelServices installInController(
      AdditionalInitialization additionalInit, List<ModelNode> bootOperations) throws Exception {
    if (additionalInit == null) {
      additionalInit = new AdditionalInitialization();
    }
    ControllerInitializer controllerInitializer = additionalInit.createControllerInitializer();
    additionalInit.setupController(controllerInitializer);

    // Initialize the controller
    ServiceContainer container =
        ServiceContainer.Factory.create("test" + counter.incrementAndGet());
    ServiceTarget target = container.subTarget();
    ControlledProcessState processState = new ControlledProcessState(true);
    List<ModelNode> extraOps = controllerInitializer.initializeBootOperations();
    List<ModelNode> allOps = new ArrayList<ModelNode>();
    if (extraOps != null) {
      allOps.addAll(extraOps);
    }
    allOps.addAll(bootOperations);
    StringConfigurationPersister persister = new StringConfigurationPersister(allOps, testParser);
    ModelControllerService svc =
        new ModelControllerService(
            additionalInit.getType(),
            mainExtension,
            controllerInitializer,
            additionalInit,
            processState,
            persister,
            additionalInit.isValidateOperations());
    ServiceBuilder<ModelController> builder =
        target.addService(ServiceName.of("ModelController"), svc);
    builder.install();

    additionalInit.addExtraServices(target);

    // sharedState = svc.state;
    svc.latch.await();
    ModelController controller = svc.getValue();
    ModelNode setup = Util.getEmptyOperation("setup", new ModelNode());
    controller.execute(setup, null, null, null);
    processState.setRunning();

    KernelServices kernelServices =
        new KernelServices(
            container, controller, persister, new OperationValidator(svc.rootRegistration));
    this.kernelServices.add(kernelServices);
    if (svc.error != null) {
      throw svc.error;
    }

    return kernelServices;
  }
Ejemplo n.º 4
0
  private AuthorizingCallbackHandler getAuthorizingCallbackHandler(final String realmName) {
    SecurityRealm realm;
    if (TEST_REALM.equals(realmName)) {
      realm = securityRealm;
    } else {
      ServiceContainer container = getContainer();
      ServiceController<?> service =
          container.getRequiredService(SecurityRealm.ServiceUtil.createServiceName(realmName));

      realm = (SecurityRealm) service.getValue();
    }

    return realm.getAuthorizingCallbackHandler(AuthMechanism.PLAIN);
  }
Ejemplo n.º 5
0
  /**
   * Test configuration
   *
   * @throws Throwable Thrown if case of an error
   */
  @Test
  public void testRegistryConfiguration() throws Throwable {
    ServiceController<?> controller =
        serviceContainer.getService(ConnectorServices.RA_REPOSITORY_SERVICE);
    assertNotNull(controller);
    ResourceAdapterRepository repository = (ResourceAdapterRepository) controller.getValue();
    assertNotNull(repository);
    Set<String> ids = repository.getResourceAdapters(javax.jms.MessageListener.class);

    assertNotNull(ids);
    int pureInflowListener = 0;
    for (String id : ids) {
      if (id.indexOf("PureInflow") != -1) {
        pureInflowListener++;
      }
    }
    assertEquals(1, pureInflowListener);

    String piId = ids.iterator().next();
    assertNotNull(piId);

    Endpoint endpoint = repository.getEndpoint(piId);
    assertNotNull(endpoint);

    List<MessageListener> listeners = repository.getMessageListeners(piId);
    assertNotNull(listeners);
    assertEquals(1, listeners.size());

    MessageListener listener = listeners.get(0);

    ActivationSpec as = listener.getActivation().createInstance();
    assertNotNull(as);
    assertNotNull(as.getResourceAdapter());
  }
 public ModuleIdentifier addExternalModule(VirtualFile externalModule) {
   ModuleIdentifier identifier =
       ModuleIdentifier.create(EXTERNAL_MODULE_PREFIX + externalModule.getPathName());
   ServiceName serviceName = ServiceModuleLoader.moduleSpecServiceName(identifier);
   ServiceController<?> controller = serviceContainer.getService(serviceName);
   if (controller == null) {
     try {
       ExternalModuleSpecService service =
           new ExternalModuleSpecService(identifier, externalModule.getPhysicalFile());
       serviceContainer.addService(serviceName, service).setInitialMode(Mode.ON_DEMAND).install();
     } catch (IOException e) {
       throw new RuntimeException(e);
     }
   }
   return identifier;
 }
  @Override
  public void unregisterService(ServiceState serviceState) {
    List<ServiceName> serviceNames = serviceState.getServiceNames();
    log.debug("Unregister service: " + serviceNames);

    AbstractBundle serviceOwner = serviceState.getServiceOwner();

    // This event is synchronously delivered before the service has completed unregistering.
    eventsPlugin.fireServiceEvent(serviceOwner, ServiceEvent.UNREGISTERING, serviceState);

    // Remove from using bundles
    for (AbstractBundle bundleState : serviceState.getUsingBundlesInternal()) {
      while (ungetService(bundleState, serviceState)) ;
    }

    // Remove from owner bundle
    serviceOwner.removeRegisteredService(serviceState);

    // Unregister name associations
    for (ServiceName serviceName : serviceNames) {
      String[] clazzes = (String[]) serviceState.getProperty(Constants.OBJECTCLASS);
      for (String clazz : clazzes) unregisterNameAssociation(clazz, serviceName);
    }

    // Remove from controller
    ServiceName rootServiceName = serviceNames.get(0);
    try {
      ServiceController<?> controller = serviceContainer.getService(rootServiceName);
      controller.setMode(Mode.REMOVE);
    } catch (RuntimeException ex) {
      log.error("Cannot remove service: " + rootServiceName, ex);
    }
  }
    private void exit() {

      if (serviceContainer != null) {
        try {
          serviceContainer.shutdown();

          serviceContainer.awaitTermination();
        } catch (RuntimeException rte) {
          throw rte;
        } catch (InterruptedException ite) {
          ite.printStackTrace();
          Thread.currentThread().interrupt();
        } catch (Exception ex) {
          ex.printStackTrace();
        }
      }
      if (controlledProcessStateService != null) {
        controlledProcessStateService.removePropertyChangeListener(processStateListener);
        controlledProcessStateService = null;
      }
      if (executorService != null) {
        try {
          executorService.shutdown();

          // 10 secs is arbitrary, but if the service container is terminated,
          // no good can happen from waiting for ModelControllerClient requests to complete
          executorService.awaitTermination(10, TimeUnit.SECONDS);
        } catch (RuntimeException rte) {
          throw rte;
        } catch (InterruptedException ite) {
          ite.printStackTrace();
          Thread.currentThread().interrupt();
        } catch (Exception ex) {
          ex.printStackTrace();
        }
      }

      if (uninstallStdIo) {
        try {
          StdioContext.uninstall();
        } catch (IllegalStateException ignored) {
          // something else already did
        }
      }

      SystemExiter.initialize(SystemExiter.Exiter.DEFAULT);
    }
 void shutdown() {
   if (allowContainerShutdown) {
     serviceContainer.shutdown();
     synchronized (shutdownInitiated) {
       shutdownInitiated.set(true);
       LOGGER.debugf("shutdownInitiated.notifyAll");
       shutdownInitiated.notifyAll();
     }
   }
 }
 void awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
   LOGGER.debugf("awaitTermination: %dms", unit.toMillis(timeout));
   synchronized (shutdownInitiated) {
     if (shutdownInitiated.get() == false) {
       LOGGER.debugf("shutdownInitiated.wait");
       shutdownInitiated.wait(2000);
     }
   }
   serviceContainer.awaitTermination(timeout == 0 ? Long.MAX_VALUE : timeout, unit);
 }
  /**
   * Uninstall the Bundle associated with this deployment.
   *
   * @param context The stop context.
   */
  public synchronized void stop(StopContext context) {
    log.tracef("Uninstalling deployment: %s", deployment);
    try {
      BundleManager bundleManager = injectedBundleManager.getValue();
      bundleManager.uninstallBundle(deployment);

      ServiceController<?> controller = context.getController();
      ServiceContainer serviceContainer = controller.getServiceContainer();
      controller.setMode(Mode.REMOVE);

      // [JBAS-8801] Undeployment leaks root deployment service
      // [TODO] remove this workaround
      ServiceName serviceName = Services.deploymentUnitName(controller.getName().getSimpleName());
      ServiceController<?> deploymentController = serviceContainer.getService(serviceName);
      if (deploymentController != null) {
        deploymentController.setMode(Mode.REMOVE);
      }
    } catch (Throwable t) {
      log.errorf(t, "Failed to uninstall deployment: %s", deployment);
    }
  }
Ejemplo n.º 12
0
 private LiveOakFactory(
     File configDir,
     File applicationsDir,
     Vertx vertx,
     String bindAddress,
     ServiceContainer serviceContainer) {
   this(
       configDir,
       applicationsDir,
       vertx,
       bindAddress,
       serviceContainer,
       serviceContainer.subTarget());
 }
 private synchronized void establishModelControllerClient(ControlledProcessState.State state) {
   ModelControllerClient newClient = null;
   if (state != ControlledProcessState.State.STOPPING && serviceContainer != null) {
     @SuppressWarnings("unchecked")
     final Value<ModelController> controllerService =
         (Value<ModelController>) serviceContainer.getService(Services.JBOSS_SERVER_CONTROLLER);
     if (controllerService != null) {
       final ModelController controller = controllerService.getValue();
       newClient = controller.createClient(executorService);
     } // else TODO use some sort of timeout and poll. A non-stopping server should install a
     // ModelController very quickly
   }
   modelControllerClient = newClient;
   currentProcessState = state;
 }
Ejemplo n.º 14
0
  @Test
  public void testMetadataConfiguration() throws Throwable {
    ServiceController<?> controller =
        serviceContainer.getService(ConnectorServices.IRONJACAMAR_MDR);
    assertNotNull(controller);
    MetadataRepository repository = (MetadataRepository) controller.getValue();
    assertNotNull(repository);
    Set<String> ids = repository.getResourceAdapters();

    assertNotNull(ids);

    String piId = ids.iterator().next();
    assertNotNull(piId);
    assertNotNull(repository.getResourceAdapter(piId));
  }
Ejemplo n.º 15
0
 @Override
 public void run() {
   final ServiceContainer sc;
   final ControlledProcessState ps;
   synchronized (this) {
     down = true;
     sc = container;
     ps = processState;
   }
   try {
     if (ps != null) {
       ps.setStopping();
     }
   } finally {
     if (sc != null) {
       SystemExiter.logBeforeExit(HostControllerLogger.ROOT_LOGGER::shutdownHookInvoked);
       final CountDownLatch latch = new CountDownLatch(1);
       sc.addTerminateListener(
           new ServiceContainer.TerminateListener() {
             @Override
             public void handleTermination(Info info) {
               latch.countDown();
             }
           });
       sc.shutdown();
       // wait for all services to finish.
       for (; ; ) {
         try {
           latch.await();
           break;
         } catch (InterruptedException e) {
         }
       }
     }
   }
 }
Ejemplo n.º 16
0
 /**
  * Start the host controller services.
  *
  * @throws Exception
  */
 public void bootstrap() throws Exception {
   final HostRunningModeControl runningModeControl = environment.getRunningModeControl();
   final ControlledProcessState processState = new ControlledProcessState(true);
   shutdownHook.setControlledProcessState(processState);
   ServiceTarget target = serviceContainer.subTarget();
   ControlledProcessStateService controlledProcessStateService =
       ControlledProcessStateService.addService(target, processState).getValue();
   RunningStateJmx.registerMBean(
       controlledProcessStateService,
       null,
       runningModeControl,
       Type.from(environment.getProcessType().name()));
   final HostControllerService hcs =
       new HostControllerService(environment, runningModeControl, authCode, processState);
   target.addService(HostControllerService.HC_SERVICE_NAME, hcs).install();
 }
Ejemplo n.º 17
0
  @Test
  public void testMetadataConfiguration() throws Throwable {
    ServiceController<?> controller =
        serviceContainer.getService(ConnectorServices.IRONJACAMAR_MDR);
    assertNotNull(controller);
    MetadataRepository repository = (MetadataRepository) controller.getValue();
    assertNotNull(repository);
    Set<String> ids = repository.getResourceAdapters();

    assertNotNull(ids);
    // on a running server it's always 2 beacause HornetQResourceAdapter is always present
    assertEquals(1, ids.size());

    for (String piId : ids) {
      assertNotNull(piId);
      System.out.println("PID:" + piId);
      assertNotNull(repository.getResourceAdapter(piId));
    }
  }
Ejemplo n.º 18
0
  public synchronized void start(StartContext context) throws StartException {
    log.debugf("Starting Arquillian Test Runner");

    final MBeanServer mbeanServer = injectedMBeanServer.getValue();
    serviceContainer = context.getController().getServiceContainer();
    serviceTarget = context.getChildTarget();
    try {
      jmxTestRunner = new ExtendedJMXTestRunner();
      jmxTestRunner.registerMBean(mbeanServer);
    } catch (Throwable t) {
      throw new StartException("Failed to start Arquillian Test Runner", t);
    }

    final ArquillianService arqService = this;
    serviceContainer.addListener(
        new AbstractServiceListener<Object>() {

          @Override
          public void serviceStarted(ServiceController<? extends Object> controller) {
            ServiceName serviceName = controller.getName();
            String simpleName = serviceName.getSimpleName();
            if (JBOSS_DEPLOYMENT.isParentOf(serviceName)
                && simpleName.equals(Phase.INSTALL.toString())) {
              ServiceName parentName = serviceName.getParent();
              ServiceController<?> parentController = serviceContainer.getService(parentName);
              DeploymentUnit depUnit = (DeploymentUnit) parentController.getValue();
              ArquillianConfig arqConfig =
                  ArquillianConfigBuilder.processDeployment(arqService, depUnit);
              if (arqConfig != null) {
                log.infof("Arquillian deployment detected: %s", arqConfig);
                ServiceBuilder<ArquillianConfig> builder =
                    arqConfig.buildService(serviceTarget, controller);
                FrameworkActivationProcessor.process(serviceContainer, builder, arqConfig);
                builder.install();
              }
            }
          }

          @Override
          public void serviceStopped(ServiceController<? extends Object> controller) {}
        });
  }
Ejemplo n.º 19
0
  /**
   * Test configuration
   *
   * @throws Throwable Thrown if case of an error
   */
  @Test
  public void testRegistryConfiguration() throws Throwable {
    ServiceController<?> controller =
        serviceContainer.getService(ConnectorServices.RA_REPOSITORY_SERVICE);
    assertNotNull(controller);
    ResourceAdapterRepository repository = (ResourceAdapterRepository) controller.getValue();
    assertNotNull(repository);
    Set<String> ids = repository.getResourceAdapters();

    assertNotNull(ids);
    // On a running server it's 3 beacause HornetQResourceAdapter is always present  + ra itself and
    // 1 actrivation from DMR
    assertEquals(2, ids.size());

    for (String piId : ids) {
      assertNotNull(piId);
      System.out.println("PID:" + piId);
      assertNotNull(repository.getResourceAdapter(piId));
    }
  }
 public static void removeService(ServiceContainer container, String contextName) {
   ServiceController<?> controller = container.getService(getServiceName(contextName));
   if (controller != null) controller.setMode(Mode.REMOVE);
 }
 boolean isShutdownComplete() {
   return serviceContainer.isShutdownComplete();
 }
    @Override
    public void start() throws ServerStartException {

      try {

        // Take control of server use of System.exit
        SystemExiter.initialize(
            new SystemExiter.Exiter() {
              @Override
              public void exit(int status) {
                StandaloneServerImpl.this.exit();
              }
            });

        // Take control of stdio
        try {
          StdioContext.install();
          uninstallStdIo = true;
        } catch (IllegalStateException ignored) {
          // already installed
        }

        // Determine the ServerEnvironment
        ServerEnvironment serverEnvironment =
            Main.determineEnvironment(
                cmdargs, systemProps, systemEnv, ServerEnvironment.LaunchType.EMBEDDED);

        Bootstrap bootstrap = Bootstrap.Factory.newInstance();

        Bootstrap.Configuration configuration = new Bootstrap.Configuration(serverEnvironment);

        /*
         * This would setup an {@link TransientConfigurationPersister} which does not persist anything
         *
        final ExtensionRegistry extensionRegistry = configuration.getExtensionRegistry();
        final Bootstrap.ConfigurationPersisterFactory configurationPersisterFactory = new Bootstrap.ConfigurationPersisterFactory() {
            @Override
            public ExtensibleConfigurationPersister createConfigurationPersister(ServerEnvironment serverEnvironment, ExecutorService executorService) {
                final QName rootElement = new QName(Namespace.CURRENT.getUriString(), "server");
                final StandaloneXml parser = new StandaloneXml(Module.getBootModuleLoader(), executorService, extensionRegistry);
                final File configurationFile = serverEnvironment.getServerConfigurationFile().getBootFile();
                XmlConfigurationPersister persister = new TransientConfigurationPersister(configurationFile, rootElement, parser, parser);
                for (Namespace namespace : Namespace.domainValues()) {
                    if (!namespace.equals(Namespace.CURRENT)) {
                        persister.registerAdditionalRootElement(new QName(namespace.getUriString(), "server"), parser);
                    }
                }
                extensionRegistry.setWriterRegistry(persister);
                return persister;
            }
        };
        configuration.setConfigurationPersisterFactory(configurationPersisterFactory);
        */

        configuration.setModuleLoader(moduleLoader);

        Future<ServiceContainer> future =
            bootstrap.startup(configuration, Collections.<ServiceActivator>emptyList());

        serviceContainer = future.get();

        executorService = Executors.newCachedThreadPool();

        @SuppressWarnings("unchecked")
        final Value<ControlledProcessStateService> processStateServiceValue =
            (Value<ControlledProcessStateService>)
                serviceContainer.getRequiredService(ControlledProcessStateService.SERVICE_NAME);
        controlledProcessStateService = processStateServiceValue.getValue();
        controlledProcessStateService.addPropertyChangeListener(processStateListener);
        establishModelControllerClient(controlledProcessStateService.getCurrentState());

      } catch (RuntimeException rte) {
        throw rte;
      } catch (Exception ex) {
        throw EmbeddedLogger.ROOT_LOGGER.cannotStartEmbeddedServer(ex);
      }
    }
  @Override
  @SuppressWarnings({"rawtypes", "unchecked"})
  public ServiceState registerService(
      AbstractBundle bundleState, String[] clazzes, Object serviceValue, Dictionary properties) {
    if (clazzes == null || clazzes.length == 0)
      throw new IllegalArgumentException("Null service classes");

    // Immediately after registration of a {@link ListenerHook}, the ListenerHook.added() method
    // will be called
    // to provide the current collection of service listeners which had been added prior to the hook
    // being registered.
    Collection<ListenerInfo> listenerInfos = null;
    if (serviceValue instanceof ListenerHook)
      listenerInfos = eventsPlugin.getServiceListenerInfos(null);

    // A temporary association of the clazz and name
    Map<ServiceName, String> associations = new HashMap<ServiceName, String>();

    // Generate the service names
    long serviceId = getNextServiceId();
    ServiceName[] serviceNames = new ServiceName[clazzes.length];
    for (int i = 0; i < clazzes.length; i++) {
      if (clazzes[i] == null)
        throw new IllegalArgumentException("Null service class at index: " + i);

      String shortName = clazzes[i].substring(clazzes[i].lastIndexOf(".") + 1);
      serviceNames[i] =
          ServiceName.of(
              "jbosgi", bundleState.getSymbolicName(), shortName, new Long(serviceId).toString());
    }

    final ServiceState serviceState =
        new ServiceState(bundleState, serviceId, serviceNames, clazzes, serviceValue, properties);
    BatchBuilder batchBuilder = serviceContainer.batchBuilder();
    Service service =
        new Service() {
          @Override
          public Object getValue() throws IllegalStateException {
            // [TODO] for injection to work this needs to be the Object value
            return serviceState;
          }

          @Override
          public void start(StartContext context) throws StartException {}

          @Override
          public void stop(StopContext context) {}
        };

    log.debug("Register service: " + Arrays.asList(serviceNames));

    ServiceName rootServiceName = serviceNames[0];
    BatchServiceBuilder serviceBuilder = batchBuilder.addService(rootServiceName, service);
    associations.put(rootServiceName, clazzes[0]);

    // Set the startup mode
    serviceBuilder.setInitialMode(Mode.AUTOMATIC);

    // Add the service aliases
    for (int i = 1; i < serviceNames.length; i++) {
      ServiceName alias = serviceNames[i];
      associations.put(alias, clazzes[1]);
      serviceBuilder.addAliases(alias);
    }

    try {
      batchBuilder.install();

      // Register the name association. We do this here
      // in case anything went wrong during the install
      for (Entry<ServiceName, String> aux : associations.entrySet()) {
        bundleState.addRegisteredService(serviceState);
        registerNameAssociation(aux.getValue(), aux.getKey());
      }
    } catch (ServiceRegistryException ex) {
      log.error("Cannot register services: " + serviceNames, ex);
    }

    // Call the newly added ListenerHook.added() method
    if (serviceValue instanceof ListenerHook) {
      ListenerHook listenerHook = (ListenerHook) serviceValue;
      listenerHook.added(listenerInfos);
    }

    // This event is synchronously delivered after the service has been registered with the
    // Framework.
    eventsPlugin.fireServiceEvent(bundleState, ServiceEvent.REGISTERED, serviceState);

    return serviceState;
  }
  public List<ServiceState> getServiceReferencesInternal(
      AbstractBundle bundleState, String clazz, Filter filter, boolean checkAssignable) {
    if (bundleState == null) throw new IllegalArgumentException("Null bundleState");

    List<ServiceName> serviceNames;
    if (clazz != null) {
      serviceNames = serviceNameMap.get(clazz);
      if (serviceNames == null) serviceNames = new ArrayList<ServiceName>();

      // Add potentially registered xservcie
      ServiceName xserviceName = ServiceName.of(ModuleContext.XSERVICE_PREFIX, clazz);
      ServiceController<?> xservice = serviceContainer.getService(xserviceName);
      if (xservice != null) serviceNames.add(xserviceName);
    } else {
      // [MSC-9] Add ability to query the ServiceContainer
      Set<ServiceName> allServiceNames = new HashSet<ServiceName>();
      for (List<ServiceName> auxList : serviceNameMap.values()) allServiceNames.addAll(auxList);

      serviceNames = new ArrayList<ServiceName>(allServiceNames);
    }

    if (serviceNames.isEmpty()) return Collections.emptyList();

    if (filter == null) filter = NoFilter.INSTANCE;

    List<ServiceState> result = new ArrayList<ServiceState>();
    for (ServiceName serviceName : serviceNames) {
      ServiceController<?> controller = serviceContainer.getService(serviceName);
      if (controller == null)
        throw new IllegalStateException("Cannot obtain service for: " + serviceName);

      Object value = controller.getValue();

      // Create the ServiceState on demand for an XService instance
      // [TODO] This should be done eagerly to keep the serviceId constant
      // [TODO] service events for XService lifecycle changes
      // [MSC-17] Canonical ServiceName string representation
      if (value instanceof ServiceState == false
          && serviceName.toString().contains(ModuleContext.XSERVICE_PREFIX)) {
        long serviceId = getNextServiceId();
        Bundle bundle = packageAdmin.getBundle(value.getClass());
        AbstractBundle owner = AbstractBundle.assertBundleState(bundle);
        value =
            new ServiceState(
                owner,
                serviceId,
                new ServiceName[] {serviceName},
                new String[] {clazz},
                value,
                null);
      }

      ServiceState serviceState = (ServiceState) value;
      if (filter.match(serviceState) == false) continue;

      Object rawValue = serviceState.getRawValue();

      checkAssignable &= (clazz != null);
      checkAssignable &= (bundleState.getBundleId() != 0);
      checkAssignable &= !(rawValue instanceof ServiceFactory);
      if (checkAssignable == false || serviceState.isAssignableTo(bundleState, clazz)) {
        result.add(serviceState);
      }
    }

    // Sort the result
    Collections.sort(result, ServiceReferenceComparator.getInstance());
    Collections.reverse(result);

    return Collections.unmodifiableList(result);
  }
 void setServiceMode(ServiceName serviceName, Mode mode) {
   ServiceController<?> controller = serviceContainer.getService(serviceName);
   if (controller == null)
     LOGGER.debugf("Cannot set mode %s on non-existing service: %s", mode, serviceName);
   else setServiceMode(controller, mode);
 }
 ServiceController<?> getRequiredService(ServiceName serviceName) {
   return serviceContainer.getRequiredService(serviceName);
 }
 @AfterClass
 public static void testServerStartupAndShutDown() throws Exception {
   container.shutdown();
   container.awaitTermination();
   Assert.assertTrue(container.isShutdownComplete());
 }