@Override
  public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    final DeploymentUnit du = phaseContext.getDeploymentUnit();

    if (GateInConfiguration.isGateInArchive(du)) {
      log.info("Module is on GateIn Extension modules list");
      final GateInConfiguration config = du.getAttachment(GateInConfigurationKey.KEY);

      final ServiceName initSvcName =
          GateInExtension.deploymentUnitName(config.getGateInEarModule(), "gatein", "init");
      final ServiceTarget target = phaseContext.getServiceTarget();

      if (du.getAttachment(GateInEarKey.KEY) != null) {
        // Install InitService with dependency on all the deployment modules reaching POST_MODULE
        // TODO: we are starting up InitService before child modules (jboss.deployment.subunit.*)
        // have gone through POST_MODULE
        final ServiceBuilder<InitService> builder =
            target
                .addService(initSvcName, new InitService(config))
                .addDependency(
                    GateInExtension.deploymentUnitName(
                        config.getGateInEarModule(), Phase.POST_MODULE));

        for (ModuleIdentifier module : config.getGateInExtModules()) {
          builder.addDependency(GateInExtension.deploymentUnitName(module, Phase.POST_MODULE));
        }
        builder.install();
        log.info("Installed " + initSvcName);
      }
      // all gatein deployment modules use InitService as barrier on POST_MODULE to ensure
      // they are all available on the classpath when init time resource loading takes place
      phaseContext.addToAttachmentList(Attachments.NEXT_PHASE_DEPS, initSvcName);
      log.info("Added NEXT_PHASE_DEP on " + initSvcName);
    }
  }
  /**
   * Add a ContextService for this module.
   *
   * @param phaseContext the deployment unit context
   * @throws org.jboss.as.server.deployment.DeploymentUnitProcessingException
   */
  public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    if (isEarDeployment(deploymentUnit)) {
      return;
    }
    final ServiceTarget serviceTarget = phaseContext.getServiceTarget();

    final ServiceName moduleContextServiceName = ContextServiceNameBuilder.module(deploymentUnit);
    final RootContextService contextService = new RootContextService();
    serviceTarget.addService(moduleContextServiceName, contextService).install();

    final BinderService<String> moduleNameBinder =
        new BinderService<String>(
            "ModuleName", Values.immediateValue(getModuleName(deploymentUnit)));
    serviceTarget
        .addService(moduleContextServiceName.append("ModuleName"), moduleNameBinder)
        .addDependency(
            moduleContextServiceName, Context.class, moduleNameBinder.getContextInjector())
        .install();

    final ContextService envContextService = new ContextService("env");
    serviceTarget
        .addService(moduleContextServiceName.append("env"), envContextService)
        .addDependency(
            moduleContextServiceName, Context.class, envContextService.getParentContextInjector())
        .install();

    phaseContext
        .getDeploymentUnit()
        .putAttachment(
            Attachments.MODULE_CONTEXT_CONFIG, new NamingContextConfig(moduleContextServiceName));
  }
  void launchServices(
      final OperationContext context,
      final PathAddress pathAddress,
      final ModelNode model,
      final ServiceVerificationHandler verificationHandler,
      final List<ServiceController<?>> newControllers)
      throws OperationFailedException {
    Handler newHandler = new Handler();

    newHandler.setClazz(
        HandlerResourceDefinition.CLASS.resolveModelAttribute(context, model).asString());

    ModelNode handler = Resource.Tools.readModel(context.readResourceFromRoot(pathAddress));

    if (handler.hasDefined(COMMON_HANDLER_PARAMETER.getName())) {
      for (ModelNode handlerParameter : handler.get(COMMON_HANDLER_PARAMETER.getName()).asList()) {
        Property property = handlerParameter.asProperty();
        String paramName = property.getName();
        String paramValue =
            HandlerParameterResourceDefinition.VALUE
                .resolveModelAttribute(context, property.getValue())
                .asString();

        KeyValueType kv = new KeyValueType();

        kv.setKey(paramName);
        kv.setValue(paramValue);

        newHandler.add(kv);
      }
    }

    SAMLHandlerService service = new SAMLHandlerService(newHandler);
    PathElement providerAlias = pathAddress.subAddress(0, pathAddress.size() - 1).getLastElement();

    ServiceTarget serviceTarget = context.getServiceTarget();
    ServiceBuilder<SAMLHandlerService> serviceBuilder =
        serviceTarget.addService(
            createServiceName(providerAlias.getValue(), newHandler.getClazz()), service);
    ServiceName serviceName;

    if (providerAlias.getKey().equals(IDENTITY_PROVIDER.getName())) {
      serviceName = IdentityProviderService.createServiceName(providerAlias.getValue());
    } else {
      serviceName = ServiceProviderService.createServiceName(providerAlias.getValue());
    }

    serviceBuilder.addDependency(
        serviceName, EntityProviderService.class, service.getEntityProviderService());

    ServiceController<SAMLHandlerService> controller =
        serviceBuilder
            .addListener(verificationHandler)
            .setInitialMode(ServiceController.Mode.PASSIVE)
            .install();

    if (newControllers != null) {
      newControllers.add(controller);
    }
  }
 private static void addClusteringServices(
     final OperationContext context, final boolean appclient) {
   if (appclient) {
     return;
   }
   ServiceTarget target = context.getServiceTarget();
   target
       .addService(RegistryCollectorService.SERVICE_NAME, new RegistryCollectorService<>())
       .setInitialMode(ServiceController.Mode.ON_DEMAND)
       .install();
   target
       .addService(
           CacheFactoryBuilderRegistryService.SERVICE_NAME,
           new CacheFactoryBuilderRegistryService<>())
       .setInitialMode(ServiceController.Mode.ON_DEMAND)
       .install();
   if (context.hasOptionalCapability(
       SingletonPolicy.CAPABILITY_NAME.concat(".default"),
       CLUSTERED_SINGLETON_CAPABILITY.getName(),
       null)) {
     final ClusteredSingletonServiceCreator singletonBarrierCreator =
         new ClusteredSingletonServiceCreator();
     target
         .addService(
             CLUSTERED_SINGLETON_CAPABILITY.getCapabilityServiceName().append("creator"),
             singletonBarrierCreator)
         .addDependency(
             context.getCapabilityServiceName(
                 SingletonPolicy.CAPABILITY_NAME, SingletonPolicy.class),
             SingletonPolicy.class,
             singletonBarrierCreator.getSingletonPolicy())
         .install();
   }
 }
  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;
  }
  protected void performRuntime(
      OperationContext context,
      ModelNode operation,
      ModelNode model,
      ServiceVerificationHandler verificationHandler,
      List<ServiceController<?>> newControllers) {
    ROOT_LOGGER.activatingSubsystem();

    ServiceTarget target = context.getServiceTarget();
    newControllers.add(
        target
            .addService(ProtocolDefaultsService.SERVICE_NAME, new ProtocolDefaultsService())
            .setInitialMode(ServiceController.Mode.ON_DEMAND)
            .install());
    String stack = operation.require(ModelKeys.DEFAULT_STACK).asString();
    InjectedValue<ChannelFactory> factory = new InjectedValue<ChannelFactory>();
    ValueService<ChannelFactory> service = new ValueService<ChannelFactory>(factory);
    newControllers.add(
        target
            .addService(ChannelFactoryService.getServiceName(null), service)
            .addDependency(
                ChannelFactoryService.getServiceName(stack), ChannelFactory.class, factory)
            .setInitialMode(ServiceController.Mode.ON_DEMAND)
            .install());
  }
  @Override
  protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model)
      throws OperationFailedException {

    ServiceRegistry registry = context.getServiceRegistry(false);
    final ServiceName serviceName =
        MessagingServices.getActiveMQServiceName(
            PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)));
    ServiceController<?> service = registry.getService(serviceName);
    if (service != null) {
      context.reloadRequired();
    } else {
      final PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));
      final String name = address.getLastElement().getValue();

      final ServiceTarget target = context.getServiceTarget();
      if (model.hasDefined(JGROUPS_CHANNEL.getName())) {
        // nothing to do, in that case, the clustering.jgroups subsystem will have setup the stack
      } else if (model.hasDefined(RemoteTransportDefinition.SOCKET_BINDING.getName())) {
        final GroupBindingService bindingService = new GroupBindingService();
        target
            .addService(
                GroupBindingService.getBroadcastBaseServiceName(serviceName).append(name),
                bindingService)
            .addDependency(
                SocketBinding.JBOSS_BINDING_NAME.append(model.get(SOCKET_BINDING).asString()),
                SocketBinding.class,
                bindingService.getBindingRef())
            .install();
      }
    }
  }
  public void deploy(final DeploymentPhaseContext phaseContext)
      throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    final List<ResourceRoot> childRoots = deploymentUnit.getAttachment(Attachments.RESOURCE_ROOTS);

    if (childRoots != null) {
      final ServiceTarget serviceTarget = phaseContext.getServiceTarget();
      for (final ResourceRoot childRoot : childRoots) {
        if (!SubDeploymentMarker.isSubDeployment(childRoot)) {
          continue;
        }
        final SubDeploymentUnitService service =
            new SubDeploymentUnitService(childRoot, deploymentUnit);
        final ServiceName serviceName =
            deploymentUnit.getServiceName().append(childRoot.getRootName());

        serviceTarget
            .addService(serviceName, service)
            .addDependency(
                Services.JBOSS_DEPLOYMENT_CHAINS,
                DeployerChains.class,
                service.getDeployerChainsInjector())
            .setInitialMode(ServiceController.Mode.ACTIVE)
            .install();
        phaseContext.addDeploymentDependency(serviceName, Attachments.SUB_DEPLOYMENTS);
      }
    }
  }
  /**
   * 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;
  }
  private void initializeModeShapeEngine(
      final OperationContext context,
      final ModelNode operation,
      ModelNode model,
      final List<ServiceController<?>> newControllers) {
    ServiceTarget target = context.getServiceTarget();

    final JBossLifeCycleListener shutdownListener = new JBossLifeCycleListener();

    engine = buildModeShapeEngine(model);

    // Engine service
    ServiceBuilder<JcrEngine> engineBuilder =
        target.addService(ModeShapeServiceNames.ENGINE, engine);
    engineBuilder.setInitialMode(ServiceController.Mode.ACTIVE);
    ServiceController<JcrEngine> controller = engineBuilder.install();
    controller.getServiceContainer().addTerminateListener(shutdownListener);
    newControllers.add(controller);

    // JNDI Binding
    final ReferenceFactoryService<JcrEngine> referenceFactoryService =
        new ReferenceFactoryService<JcrEngine>();
    final ServiceName referenceFactoryServiceName =
        ModeShapeServiceNames.ENGINE.append("reference-factory"); // $NON-NLS-1$
    final ServiceBuilder<?> referenceBuilder =
        target.addService(referenceFactoryServiceName, referenceFactoryService);
    referenceBuilder.addDependency(
        ModeShapeServiceNames.ENGINE, JcrEngine.class, referenceFactoryService.getInjector());
    referenceBuilder.setInitialMode(ServiceController.Mode.ACTIVE);

    final ContextNames.BindInfo bindInfo =
        ContextNames.bindInfoFor(ModeShapeJndiNames.JNDI_BASE_NAME);
    final BinderService binderService = new BinderService(bindInfo.getBindName());
    final ServiceBuilder<?> binderBuilder =
        target.addService(bindInfo.getBinderServiceName(), binderService);
    binderBuilder.addDependency(
        ModeShapeServiceNames.ENGINE,
        JcrEngine.class,
        new ManagedReferenceInjector<JcrEngine>(binderService.getManagedObjectInjector()));
    binderBuilder.addDependency(
        bindInfo.getParentContextServiceName(),
        ServiceBasedNamingStore.class,
        binderService.getNamingStoreInjector());
    binderBuilder.setInitialMode(ServiceController.Mode.ACTIVE);

    Logger.getLogger(getClass())
        .debug("Binding ModeShape to JNDI name '{0}'", bindInfo.getAbsoluteJndiName());

    newControllers.add(referenceBuilder.install());
    newControllers.add(binderBuilder.install());
  }
    @Override
    protected void addExtraServices(ServiceTarget target) {
      super.addExtraServices(target);
      target
          .addService(Services.JBOSS_SERVICE_MODULE_LOADER, new ServiceModuleLoader(null))
          .install();
      target
          .addService(ContextNames.JAVA_CONTEXT_SERVICE_NAME, new NamingStoreService())
          .setInitialMode(ServiceController.Mode.ACTIVE)
          .install();
      target
          .addService(ContextNames.JBOSS_CONTEXT_SERVICE_NAME, new NamingStoreService())
          .setInitialMode(ServiceController.Mode.ACTIVE)
          .install();

      target
          .addService(
              IOServices.WORKER.append("default"),
              new WorkerService(OptionMap.builder().set(Options.WORKER_IO_THREADS, 2).getMap()))
          .setInitialMode(ServiceController.Mode.ACTIVE)
          .install();

      target
          .addService(
              IOServices.WORKER.append("non-default"),
              new WorkerService(OptionMap.builder().set(Options.WORKER_IO_THREADS, 2).getMap()))
          .setInitialMode(ServiceController.Mode.ACTIVE)
          .install();

      target
          .addService(
              IOServices.BUFFER_POOL.append("default"), new BufferPoolService(2048, 2048, true))
          .setInitialMode(ServiceController.Mode.ACTIVE)
          .install();
      // ListenerRegistry.Listener listener = new ListenerRegistry.Listener("http", "default",
      // "default",
      // InetSocketAddress.createUnresolved("localhost",8080));
      target
          .addService(HttpListenerAdd.REGISTRY_SERVICE_NAME, new HttpListenerRegistryService())
          .setInitialMode(ServiceController.Mode.ACTIVE)
          .install();

      target
          .addService(
              SecurityRealm.ServiceUtil.createServiceName("UndertowRealm"),
              new SecurityRealmService("UndertowRealm", false))
          .setInitialMode(ServiceController.Mode.ACTIVE)
          .install();
      target
          .addService(
              SecurityRealm.ServiceUtil.createServiceName("other"),
              new SecurityRealmService("other", false))
          .setInitialMode(ServiceController.Mode.ACTIVE)
          .install();
    }
    @Override
    protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model)
        throws OperationFailedException {
      ServiceTarget serviceTarget = context.getServiceTarget();
      RuntimeCapability<Void> runtimeCapability =
          REALM_MAPPER_RUNTIME_CAPABILITY.fromBaseCapability(context.getCurrentAddressValue());
      ServiceName realmMapperName = runtimeCapability.getCapabilityServiceName(RealmMapper.class);

      final String pattern = PATTERN.resolveModelAttribute(context, model).asString();

      ModelNode realmMapList = REALM_REALM_MAP.resolveModelAttribute(context, model);
      Set<String> names = realmMapList.keys();
      final Map<String, String> realmRealmMap = new HashMap<String, String>(names.size());
      names.forEach((String s) -> realmRealmMap.put(s, realmMapList.require(s).asString()));

      String delegateRealmMapper = asStringIfDefined(context, DELEGATE_REALM_MAPPER, model);

      final InjectedValue<RealmMapper> delegateRealmMapperInjector =
          new InjectedValue<RealmMapper>();

      TrivialService<RealmMapper> realmMapperService =
          new TrivialService<RealmMapper>(
              () -> {
                RealmMapper delegate = delegateRealmMapperInjector.getOptionalValue();
                Pattern compiledPattern = Pattern.compile(pattern);
                if (delegate == null) {
                  return new MappedRegexRealmMapper(compiledPattern, realmRealmMap);
                } else {
                  return new MappedRegexRealmMapper(compiledPattern, delegate, realmRealmMap);
                }
              });

      ServiceBuilder<RealmMapper> realmMapperBuilder =
          serviceTarget.addService(realmMapperName, realmMapperService);

      if (delegateRealmMapper != null) {
        String delegateCapabilityName =
            RuntimeCapability.buildDynamicCapabilityName(
                REALM_MAPPER_CAPABILITY, delegateRealmMapper);
        ServiceName delegateServiceName =
            context.getCapabilityServiceName(delegateCapabilityName, RealmMapper.class);

        realmMapperBuilder.addDependency(
            delegateServiceName, RealmMapper.class, delegateRealmMapperInjector);
      }

      commonDependencies(realmMapperBuilder).setInitialMode(Mode.LAZY).install();
    }
 public static void install(
     final ServiceTarget serviceTarget, final Endpoint endpoint, final DeploymentUnit unit) {
   final ServiceName serviceName = getServiceName(unit, endpoint.getShortName());
   final EndpointService service = new EndpointService(endpoint, serviceName);
   final ServiceBuilder<Endpoint> builder = serviceTarget.addService(serviceName, service);
   builder.addDependency(
       DependencyType.REQUIRED,
       SecurityDomainService.SERVICE_NAME.append(getDeploymentSecurityDomainName(endpoint)),
       SecurityDomainContext.class,
       service.getSecurityDomainContextInjector());
   builder.addDependency(
       DependencyType.REQUIRED,
       WSServices.REGISTRY_SERVICE,
       EndpointRegistry.class,
       service.getEndpointRegistryInjector());
   builder.addDependency(
       DependencyType.REQUIRED,
       WSServices.PORT_COMPONENT_LINK_SERVICE,
       WebAppController.class,
       service.getPclWebAppControllerInjector());
   builder.addDependency(
       DependencyType.OPTIONAL,
       MBEAN_SERVER_NAME,
       MBeanServer.class,
       service.getMBeanServerInjector());
   builder.setInitialMode(Mode.ACTIVE);
   builder.install();
 }
 private static ServiceName installSessionManagerFactory(
     ServiceTarget target,
     ServiceName deploymentServiceName,
     String deploymentName,
     Module module,
     JBossWebMetaData metaData) {
   ServiceName name = deploymentServiceName.append("session");
   if (metaData.getDistributable() != null) {
     DistributableSessionManagerFactoryBuilder sessionManagerFactoryBuilder =
         new DistributableSessionManagerFactoryBuilderValue().getValue();
     if (sessionManagerFactoryBuilder != null) {
       sessionManagerFactoryBuilder
           .build(
               target,
               name,
               new SimpleDistributableSessionManagerConfiguration(
                   metaData, deploymentName, module))
           .setInitialMode(Mode.ON_DEMAND)
           .install();
       return name;
     }
     // Fallback to local session manager if server does not support clustering
     UndertowLogger.ROOT_LOGGER.clusteringNotSupported();
   }
   Integer maxActiveSessions = metaData.getMaxActiveSessions();
   InMemorySessionManagerFactory factory =
       (maxActiveSessions != null)
           ? new InMemorySessionManagerFactory(maxActiveSessions.intValue())
           : new InMemorySessionManagerFactory();
   target
       .addService(name, new ValueService<>(new ImmediateValue<>(factory)))
       .setInitialMode(Mode.ON_DEMAND)
       .install();
   return name;
 }
  Collection<ServiceController<?>> installChannelServices(
      ServiceTarget target,
      String containerName,
      String cluster,
      String stack,
      ServiceVerificationHandler verificationHandler) {

    ServiceName name = ChannelService.getServiceName(containerName);
    ContextNames.BindInfo bindInfo = createChannelBinding(containerName);
    BinderService binder = new BinderService(bindInfo.getBindName());
    ServiceController<?> binderService =
        target
            .addService(bindInfo.getBinderServiceName(), binder)
            .addAliases(ContextNames.JAVA_CONTEXT_SERVICE_NAME.append(bindInfo.getBindName()))
            .addDependency(
                name,
                Channel.class,
                new ManagedReferenceInjector<Channel>(binder.getManagedObjectInjector()))
            .addDependency(
                bindInfo.getParentContextServiceName(),
                ServiceBasedNamingStore.class,
                binder.getNamingStoreInjector())
            .setInitialMode(ServiceController.Mode.PASSIVE)
            .install();

    InjectedValue<ChannelFactory> channelFactory = new InjectedValue<>();
    ServiceController<?> channelService =
        AsynchronousService.addService(target, name, new ChannelService(cluster, channelFactory))
            .addDependency(
                ChannelFactoryService.getServiceName(stack), ChannelFactory.class, channelFactory)
            .setInitialMode(ServiceController.Mode.ON_DEMAND)
            .install();

    return Arrays.asList(binderService, channelService);
  }
 @Override
 public ServiceBuilder<T> build(ServiceTarget target) {
   return target
       .addService(this.name, new ValueService<>(this.value))
       .addDependency(this.targetName, this.targetClass, this.value)
       .setInitialMode(ServiceController.Mode.ON_DEMAND);
 }
 /**
  * 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();
 }
  private void addLdapService(
      OperationContext context,
      ModelNode ldap,
      String realmName,
      ServiceTarget serviceTarget,
      List<ServiceController<?>> newControllers,
      ServiceBuilder<?> realmBuilder,
      Injector<CallbackHandlerService> injector,
      boolean shareConnection)
      throws OperationFailedException {
    ServiceName ldapServiceName = UserLdapCallbackHandler.ServiceUtil.createServiceName(realmName);

    final String baseDn =
        LdapAuthenticationResourceDefinition.BASE_DN
            .resolveModelAttribute(context, ldap)
            .asString();
    ModelNode node =
        LdapAuthenticationResourceDefinition.USERNAME_FILTER.resolveModelAttribute(context, ldap);
    final String usernameAttribute = node.isDefined() ? node.asString() : null;
    node =
        LdapAuthenticationResourceDefinition.ADVANCED_FILTER.resolveModelAttribute(context, ldap);
    final String advancedFilter = node.isDefined() ? node.asString() : null;
    final boolean recursive =
        LdapAuthenticationResourceDefinition.RECURSIVE
            .resolveModelAttribute(context, ldap)
            .asBoolean();
    final boolean allowEmptyPasswords =
        LdapAuthenticationResourceDefinition.ALLOW_EMPTY_PASSWORDS
            .resolveModelAttribute(context, ldap)
            .asBoolean();
    final String userDn =
        LdapAuthenticationResourceDefinition.USER_DN
            .resolveModelAttribute(context, ldap)
            .asString();
    UserLdapCallbackHandler ldapCallbackHandler =
        new UserLdapCallbackHandler(
            baseDn,
            usernameAttribute,
            advancedFilter,
            recursive,
            userDn,
            allowEmptyPasswords,
            shareConnection);

    ServiceBuilder<?> ldapBuilder = serviceTarget.addService(ldapServiceName, ldapCallbackHandler);
    String connectionManager =
        LdapAuthenticationResourceDefinition.CONNECTION
            .resolveModelAttribute(context, ldap)
            .asString();
    LdapConnectionManagerService.ServiceUtil.addDependency(
        ldapBuilder, ldapCallbackHandler.getConnectionManagerInjector(), connectionManager, false);

    final ServiceController<?> serviceController = ldapBuilder.setInitialMode(ON_DEMAND).install();
    if (newControllers != null) {
      newControllers.add(serviceController);
    }

    CallbackHandlerService.ServiceUtil.addDependency(
        realmBuilder, injector, ldapServiceName, false);
  }
Exemple #19
0
  @SuppressWarnings("rawtypes")
  ServiceController<?> installJndiService(
      ServiceTarget target,
      String containerName,
      String cacheName,
      String jndiNameString,
      ServiceVerificationHandler verificationHandler) {

    final String jndiName =
        InfinispanJndiName.createCacheJndiNameOrDefault(jndiNameString, containerName, cacheName);
    final ServiceName cacheServiceName = CacheService.getServiceName(containerName, cacheName);
    final ContextNames.BindInfo bindInfo = ContextNames.bindInfoFor(jndiName);
    final BinderService binder = new BinderService(bindInfo.getBindName());
    return target
        .addService(bindInfo.getBinderServiceName(), binder)
        .addAliases(ContextNames.JAVA_CONTEXT_SERVICE_NAME.append(jndiName))
        .addDependency(
            cacheServiceName,
            Cache.class,
            new ManagedReferenceInjector<Cache>(binder.getManagedObjectInjector()))
        .addDependency(
            bindInfo.getParentContextServiceName(),
            ServiceBasedNamingStore.class,
            binder.getNamingStoreInjector())
        .setInitialMode(ServiceController.Mode.PASSIVE)
        .install();
  }
  public static ServiceController<?> addService(
      ServiceTarget serviceTarget,
      HostPathManagerService service,
      HostControllerEnvironment hostEnvironment) {
    ServiceBuilder<?> serviceBuilder = serviceTarget.addService(SERVICE_NAME, service);

    service.addHardcodedAbsolutePath(
        serviceTarget,
        HostControllerEnvironment.HOME_DIR,
        hostEnvironment.getHomeDir().getAbsolutePath());
    service.addHardcodedAbsolutePath(
        serviceTarget,
        HostControllerEnvironment.DOMAIN_CONFIG_DIR,
        hostEnvironment.getDomainConfigurationDir().getAbsolutePath());
    service.addHardcodedAbsolutePath(
        serviceTarget,
        HostControllerEnvironment.DOMAIN_DATA_DIR,
        hostEnvironment.getDomainDataDir().getAbsolutePath());
    service.addHardcodedAbsolutePath(
        serviceTarget,
        HostControllerEnvironment.DOMAIN_LOG_DIR,
        hostEnvironment.getDomainLogDir().getAbsolutePath());
    service.addHardcodedAbsolutePath(
        serviceTarget,
        HostControllerEnvironment.DOMAIN_TEMP_DIR,
        hostEnvironment.getDomainTempDir().getAbsolutePath());
    service.addHardcodedAbsolutePath(
        serviceTarget,
        HostControllerEnvironment.CONTROLLER_TEMP_DIR,
        hostEnvironment.getDomainTempDir().getAbsolutePath());

    return serviceBuilder.install();
  }
  ServiceController<?> installJndiService(
      ServiceTarget target,
      String containerName,
      String jndiName,
      ServiceVerificationHandler verificationHandler) {

    final ServiceName containerServiceName =
        EmbeddedCacheManagerService.getServiceName(containerName);
    final ContextNames.BindInfo binding = createCacheContainerBinding(jndiName, containerName);

    final BinderService binder = new BinderService(binding.getBindName());
    return target
        .addService(binding.getBinderServiceName(), binder)
        .addAliases(ContextNames.JAVA_CONTEXT_SERVICE_NAME.append(binding.getBindName()))
        .addDependency(
            containerServiceName,
            CacheContainer.class,
            new ManagedReferenceInjector<CacheContainer>(binder.getManagedObjectInjector()))
        .addDependency(
            binding.getParentContextServiceName(),
            ServiceBasedNamingStore.class,
            binder.getNamingStoreInjector())
        .setInitialMode(ServiceController.Mode.PASSIVE)
        .install();
  }
  private void addUsersService(
      OperationContext context,
      ModelNode users,
      String realmName,
      ServiceTarget serviceTarget,
      List<ServiceController<?>> newControllers,
      ServiceBuilder<?> realmBuilder,
      Injector<CallbackHandlerService> injector)
      throws OperationFailedException {
    ServiceName usersServiceName =
        UserDomainCallbackHandler.ServiceUtil.createServiceName(realmName);

    UserDomainCallbackHandler usersCallbackHandler =
        new UserDomainCallbackHandler(realmName, unmaskUsersPasswords(context, users));

    ServiceBuilder<?> usersBuilder =
        serviceTarget.addService(usersServiceName, usersCallbackHandler);

    final ServiceController<?> serviceController =
        usersBuilder.setInitialMode(ServiceController.Mode.ON_DEMAND).install();
    if (newControllers != null) {
      newControllers.add(serviceController);
    }

    CallbackHandlerService.ServiceUtil.addDependency(
        realmBuilder, injector, usersServiceName, false);
  }
  public ServiceBuilder<Void> install(ServiceTarget serviceTarget) {
    final AbstractInstallComplete installComplete = this;
    final ServiceBuilder<Void> builder = serviceTarget.addService(getServiceName(), this);
    tracker =
        new ServiceTracker<Bundle>() {

          @Override
          protected boolean allServicesAdded(Set<ServiceName> trackedServices) {
            return installComplete.allServicesAdded(trackedServices);
          }

          @Override
          protected void serviceStarted(ServiceController<? extends Bundle> controller) {
            Bundle bundle = controller.getValue();
            installedBundles.add(bundle);
          }

          @Override
          protected void complete() {
            builder.install();
          }
        };
    configureDependencies(builder);
    return builder;
  }
  private void addSecretService(
      OperationContext context,
      ModelNode secret,
      String realmName,
      ServiceTarget serviceTarget,
      List<ServiceController<?>> newControllers,
      ServiceBuilder<?> realmBuilder,
      Injector<CallbackHandlerFactory> injector)
      throws OperationFailedException {
    ServiceName secretServiceName = SecretIdentityService.ServiceUtil.createServiceName(realmName);

    ModelNode resolvedValueNode =
        SecretServerIdentityResourceDefinition.VALUE.resolveModelAttribute(context, secret);
    boolean base64 =
        secret.get(SecretServerIdentityResourceDefinition.VALUE.getName()).getType()
            != ModelType.EXPRESSION;

    SecretIdentityService sis = new SecretIdentityService(resolvedValueNode.asString(), base64);
    final ServiceController<CallbackHandlerFactory> serviceController =
        serviceTarget.addService(secretServiceName, sis).setInitialMode(ON_DEMAND).install();
    if (newControllers != null) {
      newControllers.add(serviceController);
    }

    CallbackHandlerFactory.ServiceUtil.addDependency(
        realmBuilder, injector, secretServiceName, false);
  }
Exemple #25
0
  public void installServices(
      final ServiceVerificationHandler verificationHandler,
      final List<ServiceController<?>> newControllers,
      final String name,
      final ServiceTarget serviceTarget,
      final ServiceName hqServiceName,
      final String selector,
      final boolean durable,
      final String[] jndiBindings) {
    final JMSQueueService service = new JMSQueueService(name, selector, durable, jndiBindings);

    final ServiceName serviceName =
        JMSServices.getJmsQueueBaseServiceName(hqServiceName).append(name);
    final ServiceBuilder<Void> serviceBuilder =
        serviceTarget
            .addService(serviceName, service)
            .addDependency(HornetQActivationService.getHornetQActivationServiceName(hqServiceName))
            .addDependency(
                JMSServices.getJmsManagerBaseServiceName(hqServiceName),
                JMSServerManager.class,
                service.getJmsServer())
            .setInitialMode(Mode.PASSIVE);
    org.jboss.as.server.Services.addServerExecutorDependency(
        serviceBuilder, service.getExecutorInjector(), false);
    if (verificationHandler != null) {
      serviceBuilder.addListener(verificationHandler);
    }

    final ServiceController<Void> controller = serviceBuilder.install();
    if (newControllers != null) {
      newControllers.add(controller);
    }
  }
  private void addLocalService(
      OperationContext context,
      ModelNode local,
      String realmName,
      ServiceTarget serviceTarget,
      List<ServiceController<?>> newControllers,
      ServiceBuilder<?> realmBuilder,
      Injector<CallbackHandlerService> injector)
      throws OperationFailedException {
    ServiceName localServiceName =
        LocalCallbackHandlerService.ServiceUtil.createServiceName(realmName);

    ModelNode node =
        LocalAuthenticationResourceDefinition.DEFAULT_USER.resolveModelAttribute(context, local);
    String defaultUser = node.isDefined() ? node.asString() : null;
    node =
        LocalAuthenticationResourceDefinition.ALLOWED_USERS.resolveModelAttribute(context, local);
    String allowedUsers = node.isDefined() ? node.asString() : null;
    LocalCallbackHandlerService localCallbackHandler =
        new LocalCallbackHandlerService(defaultUser, allowedUsers);

    ServiceBuilder<?> jaasBuilder =
        serviceTarget.addService(localServiceName, localCallbackHandler);
    final ServiceController<?> serviceController = jaasBuilder.setInitialMode(ON_DEMAND).install();
    if (newControllers != null) {
      newControllers.add(serviceController);
    }

    CallbackHandlerService.ServiceUtil.addDependency(
        realmBuilder, injector, localServiceName, false);
  }
 static ServiceController<StandardContext> addService(ServiceTarget serviceTarget) {
   HttpServiceActivator service = new HttpServiceActivator();
   ServiceBuilder<StandardContext> builder =
       serviceTarget.addService(JBOSS_WEB_HTTPSERVICE_FACTORY, service);
   builder.addDependency(
       ServerEnvironmentService.SERVICE_NAME,
       ServerEnvironment.class,
       service.injectedServerEnvironment);
   builder.addDependency(
       PathManagerService.SERVICE_NAME, PathManager.class, service.injectedPathManager);
   builder.addDependency(
       WebSubsystemServices.JBOSS_WEB_HOST.append(VIRTUAL_HOST),
       VirtualHost.class,
       service.injectedVirtualHost);
   builder.addDependency(
       WebSubsystemServices.JBOSS_WEB, WebServer.class, service.injectedWebServer);
   builder.addDependency(
       DependencyType.OPTIONAL,
       HttpManagementService.SERVICE_NAME,
       HttpManagement.class,
       service.injectedHttpManagement);
   builder.addDependency(
       Services.FRAMEWORK_ACTIVE, BundleContext.class, service.injectedSystemContext);
   builder.setInitialMode(Mode.PASSIVE);
   return builder.install();
 }
  ServiceController<?> installContainerService(
      ServiceTarget target,
      String containerName,
      ServiceName[] aliases,
      Transport transport,
      ServiceController.Mode initialMode,
      ServiceVerificationHandler verificationHandler) {

    final ServiceName containerServiceName =
        EmbeddedCacheManagerService.getServiceName(containerName);
    final ServiceName configServiceName =
        EmbeddedCacheManagerConfigurationService.getServiceName(containerName);
    final InjectedValue<EmbeddedCacheManagerConfiguration> config = new InjectedValue<>();
    final Service<EmbeddedCacheManager> service = new EmbeddedCacheManagerService(config);
    ServiceBuilder<EmbeddedCacheManager> builder =
        target
            .addService(containerServiceName, service)
            .addDependency(configServiceName, EmbeddedCacheManagerConfiguration.class, config)
            .addAliases(aliases)
            .setInitialMode(initialMode);
    if (transport != null) {
      builder.addDependency(ChannelService.getServiceName(containerName));
    }
    return builder.install();
  }
  private void addPlugInAuthorizationService(
      OperationContext context,
      ModelNode model,
      String realmName,
      ServiceTarget serviceTarget,
      List<ServiceController<?>> newControllers,
      ServiceBuilder<?> realmBuilder,
      InjectedValue<SubjectSupplementalService> injector)
      throws OperationFailedException {

    ServiceName plugInServiceName =
        PlugInSubjectSupplemental.ServiceUtil.createServiceName(realmName);
    final String pluginName =
        PlugInAuthorizationResourceDefinition.NAME.resolveModelAttribute(context, model).asString();
    final Map<String, String> properties = resolveProperties(context, model);
    PlugInSubjectSupplemental plugInSubjectSupplemental =
        new PlugInSubjectSupplemental(realmName, pluginName, properties);

    ServiceBuilder<?> plugInBuilder =
        serviceTarget.addService(plugInServiceName, plugInSubjectSupplemental);
    PlugInLoaderService.ServiceUtil.addDependency(
        plugInBuilder, plugInSubjectSupplemental.getPlugInLoaderServiceValue(), realmName, false);

    final ServiceController<?> serviceController =
        plugInBuilder.setInitialMode(ON_DEMAND).install();
    if (newControllers != null) {
      newControllers.add(serviceController);
    }

    SubjectSupplementalService.ServiceUtil.addDependency(
        realmBuilder, injector, plugInServiceName, false);
  }
  private void addJaasService(
      OperationContext context,
      ModelNode jaas,
      String realmName,
      ServiceTarget serviceTarget,
      List<ServiceController<?>> newControllers,
      boolean injectServerManager,
      ServiceBuilder<?> realmBuilder,
      Injector<CallbackHandlerService> injector)
      throws OperationFailedException {
    ServiceName jaasServiceName = JaasCallbackHandler.ServiceUtil.createServiceName(realmName);
    String name =
        JaasAuthenticationResourceDefinition.NAME.resolveModelAttribute(context, jaas).asString();
    JaasCallbackHandler jaasCallbackHandler = new JaasCallbackHandler(name);

    ServiceBuilder<?> jaasBuilder = serviceTarget.addService(jaasServiceName, jaasCallbackHandler);
    if (injectServerManager) {
      jaasBuilder.addDependency(
          ServiceName.JBOSS.append("security", "simple-security-manager"),
          ServerSecurityManager.class,
          jaasCallbackHandler.getSecurityManagerValue());
    }

    final ServiceController<?> sc = jaasBuilder.setInitialMode(ON_DEMAND).install();
    if (newControllers != null) {
      newControllers.add(sc);
    }

    CallbackHandlerService.ServiceUtil.addDependency(
        realmBuilder, injector, jaasServiceName, false);
  }