org.jboss.msc.service.ServiceBuilder Java Examples

The following examples show how to use org.jboss.msc.service.ServiceBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ModuleResolvePhaseService.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static void installService(final ServiceTarget serviceTarget, final ModuleIdentifier moduleIdentifier, int phaseNumber, final Set<ModuleDependency> nextPhaseIdentifiers, final Set<ModuleIdentifier> nextAlreadySeen) {
    final ModuleResolvePhaseService nextPhaseService = new ModuleResolvePhaseService(moduleIdentifier, nextAlreadySeen, phaseNumber);
    ServiceBuilder<ModuleResolvePhaseService> builder = serviceTarget.addService(moduleSpecServiceName(moduleIdentifier, phaseNumber), nextPhaseService);
    for (ModuleDependency module : nextPhaseIdentifiers) {
        builder.addDependency(ServiceModuleLoader.moduleSpecServiceName(module.getIdentifier()), ModuleDefinition.class, new Injector<ModuleDefinition>() {

            ModuleDefinition definition;

            @Override
            public synchronized void inject(final ModuleDefinition o) throws InjectionException {
                nextPhaseService.getModuleSpecs().add(o);
                this.definition = o;
            }

            @Override
            public synchronized void uninject() {
                nextPhaseService.getModuleSpecs().remove(definition);
                this.definition = null;
            }
        });
    }
    builder.install();
}
 
Example #2
Source File: SecurityRealmAddHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Supplier<SubjectSupplementalService> addPropertiesAuthorizationService(OperationContext context, ModelNode properties,
                                               String realmName, ServiceTarget serviceTarget, ServiceBuilder<?> realmBuilder) throws OperationFailedException {
    final ServiceName propsServiceName = PropertiesSubjectSupplemental.ServiceUtil.createServiceName(realmName);
    final String path = PropertiesAuthorizationResourceDefinition.PATH.resolveModelAttribute(context, properties).asString();
    final ModelNode relativeToNode = PropertiesAuthorizationResourceDefinition.RELATIVE_TO.resolveModelAttribute(context, properties);
    final String relativeTo = relativeToNode.isDefined() ? relativeToNode.asString() : null;

    final ServiceBuilder<?> builder = serviceTarget.addService(propsServiceName);
    final Consumer<SubjectSupplementalService> sssConsumer = builder.provides(propsServiceName);
    Supplier<PathManager> pmSupplier = null;
    if (relativeTo != null) {
        pmSupplier = builder.requires(context.getCapabilityServiceName(PATH_MANAGER_CAPABILITY, PathManager.class));
        builder.requires(pathName(relativeTo));
    }
    builder.setInstance(new PropertiesSubjectSupplemental(sssConsumer, pmSupplier, realmName, path, relativeTo));
    builder.setInitialMode(ON_DEMAND);
    builder.install();

    return SubjectSupplementalService.ServiceUtil.requires(realmBuilder, propsServiceName);
}
 
Example #3
Source File: ConsoleAvailabilityUnitTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Before
public void setupController() throws InterruptedException {
    container = ServiceContainer.Factory.create("test");
    ServiceTarget target = container.subTarget();

    this.controlledProcessState = new ControlledProcessState(true);

    ServiceBuilder<?> sb = target.addService(ServiceName.of("ModelController"));
    this.caSupplier = sb.requires(CONSOLE_AVAILABILITY_CAPABILITY.getCapabilityServiceName());

    ConsoleAvailabilityControllerTmp caService = new ConsoleAvailabilityControllerTmp(controlledProcessState);

    ControlledProcessStateService.addService(target, controlledProcessState);
    ConsoleAvailabilityService.addService(target, () -> {});

    sb.setInstance(caService)
            .install();

    caService.awaitStartup(30, TimeUnit.SECONDS);
}
 
Example #4
Source File: SecurityRealmAddHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Supplier<CallbackHandlerFactory> addSecretService(OperationContext context, ModelNode secret, String realmName, ServiceTarget serviceTarget,
                              ServiceBuilder<?> realmBuilder) throws OperationFailedException {
    final ServiceName secretServiceName = SecretIdentityService.ServiceUtil.createServiceName(realmName);
    final ModelNode resolvedValueNode = SecretServerIdentityResourceDefinition.VALUE.resolveModelAttribute(context, secret);
    boolean base64 = secret.get(SecretServerIdentityResourceDefinition.VALUE.getName()).getType() != ModelType.EXPRESSION;
    final ServiceBuilder<?> builder = serviceTarget.addService(secretServiceName);
    final Consumer<CallbackHandlerFactory> chfConsumer = builder.provides(secretServiceName);
    ExceptionSupplier<CredentialSource, Exception> credentialSourceSupplier = null;
    if (secret.hasDefined(CredentialReference.CREDENTIAL_REFERENCE)) {
        String keySuffix = SERVER_IDENTITY + KEY_DELIMITER + SECRET;
        credentialSourceSupplier = CredentialReference.getCredentialSourceSupplier(context, SecretServerIdentityResourceDefinition.CREDENTIAL_REFERENCE, secret, builder, keySuffix);
    }
    SecretIdentityService sis;
    if (secret.hasDefined(CredentialReference.CREDENTIAL_REFERENCE)) {
        sis = new SecretIdentityService(chfConsumer, credentialSourceSupplier, resolvedValueNode.asString(), false);
    } else {
        sis = new SecretIdentityService(chfConsumer, credentialSourceSupplier, resolvedValueNode.asString(), base64);
    }
    builder.setInstance(sis);
    builder.setInitialMode(ON_DEMAND);
    builder.install();

    return CallbackHandlerFactory.ServiceUtil.requires(realmBuilder, secretServiceName);
}
 
Example #5
Source File: MscManagedProcessEngineController.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
public static void initializeServiceBuilder(ManagedProcessEngineMetadata processEngineConfiguration, MscManagedProcessEngineController service,
        ServiceBuilder<ProcessEngine> serviceBuilder, String jobExecutorName) {

  ContextNames.BindInfo datasourceBindInfo = ContextNames.bindInfoFor(processEngineConfiguration.getDatasourceJndiName());
  serviceBuilder.addDependency(ServiceName.JBOSS.append("txn").append("TransactionManager"), TransactionManager.class, service.getTransactionManagerInjector())
    .addDependency(datasourceBindInfo.getBinderServiceName(), DataSourceReferenceFactoryService.class, service.getDatasourceBinderServiceInjector())
    .addDependency(ServiceNames.forMscRuntimeContainerDelegate(), MscRuntimeContainerDelegate.class, service.getRuntimeContainerDelegateInjector())
    .addDependency(ServiceNames.forMscRuntimeContainerJobExecutorService(jobExecutorName), MscRuntimeContainerJobExecutor.class, service.getMscRuntimeContainerJobExecutorInjector())
    .addDependency(ServiceNames.forMscExecutorService())
    .setInitialMode(Mode.ACTIVE);

  if(processEngineConfiguration.isDefault()) {
    serviceBuilder.addAliases(ServiceNames.forDefaultProcessEngine());
  }

  JBossCompatibilityExtension.addServerExecutorDependency(serviceBuilder, service.getExecutorInjector(), false);

}
 
Example #6
Source File: ModuleSpecProcessor.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void installAliases(final ModuleSpecification moduleSpecification, final ModuleIdentifier moduleIdentifier, final DeploymentUnit deploymentUnit, final DeploymentPhaseContext phaseContext) {

        ModuleLoader moduleLoader = deploymentUnit.getAttachment(Attachments.SERVICE_MODULE_LOADER);
        for (final ModuleIdentifier alias : moduleSpecification.getAliases()) {
            final ServiceName moduleSpecServiceName = ServiceModuleLoader.moduleSpecServiceName(alias);
            final ModuleSpec spec = ModuleSpec.buildAlias(alias, moduleIdentifier).create();

            HashSet<ModuleDependency> dependencies = new HashSet<>(moduleSpecification.getAllDependencies());
            //we need to add the module we are aliasing as a dependency, to make sure that it will be resolved
            dependencies.add(new ModuleDependency(moduleLoader, moduleIdentifier, false, false, false, false));
            ModuleDefinition moduleDefinition = new ModuleDefinition(alias, dependencies, spec);

            final ValueService<ModuleDefinition> moduleSpecService = new ValueService<>(new ImmediateValue<>(moduleDefinition));
            final ServiceBuilder sb = phaseContext.getServiceTarget().addService(moduleSpecServiceName, moduleSpecService);
            sb.requires(deploymentUnit.getServiceName());
            sb.requires(phaseContext.getPhaseServiceName());
            sb.setInitialMode(Mode.ON_DEMAND);
            sb.install();

            ModuleLoadService.installAliases(phaseContext.getServiceTarget(), alias, Collections.singletonList(moduleIdentifier));

            ModuleResolvePhaseService.installService(phaseContext.getServiceTarget(), moduleDefinition);
        }
    }
 
Example #7
Source File: PrincipalTransformerDefinitions.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
static ResourceDefinition getRegexPrincipalTransformerDefinition() {
    final AttributeDefinition[] attributes = new AttributeDefinition[] { PATTERN, REPLACEMENT, REPLACE_ALL };
    AbstractAddStepHandler add = new TrivialAddHandler<PrincipalTransformer>(PrincipalTransformer.class, attributes, PRINCIPAL_TRANSFORMER_RUNTIME_CAPABILITY) {

        @Override
        protected ValueSupplier<PrincipalTransformer> getValueSupplier(ServiceBuilder<PrincipalTransformer> serviceBuilder,
                OperationContext context, ModelNode model) throws OperationFailedException {

            final Pattern pattern     = Pattern.compile(PATTERN.resolveModelAttribute(context, model).asString());
            final String  replacement = REPLACEMENT.resolveModelAttribute(context, model).asString();
            final boolean replaceAll  = REPLACE_ALL.resolveModelAttribute(context, model).asBoolean();

            return () -> PrincipalTransformer.from(new RegexNameRewriter(pattern, replacement, replaceAll).asPrincipalRewriter());
        }
    };

    return new TrivialResourceDefinition(REGEX_PRINCIPAL_TRANSFORMER, add, attributes, PRINCIPAL_TRANSFORMER_RUNTIME_CAPABILITY);
}
 
Example #8
Source File: RemotingServices.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Deprecated
public static void installConnectorServicesForNetworkInterfaceBinding(final ServiceTarget serviceTarget,
                                                                      final ServiceName endpointName,
                                                                      final String connectorName,
                                                                      final ServiceName networkInterfaceBindingName,
                                                                      final int port,
                                                                      final OptionMap connectorPropertiesOptionMap,
                                                                      final ServiceName securityRealm,
                                                                      final ServiceName saslAuthenticationFactory,
                                                                      final ServiceName sslContext,
                                                                      final ServiceName socketBindingManager) {
    final ServiceName serviceName= serverServiceName(connectorName);
    final ServiceBuilder<?> builder = serviceTarget.addService(serviceName);
    final Consumer<AcceptingChannel<StreamConnection>> streamServerConsumer = builder.provides(serviceName);
    final Supplier<Endpoint> eSupplier = builder.requires(endpointName);
    final Supplier<SecurityRealm> srSupplier = securityRealm != null ? builder.requires(securityRealm) : null;
    final Supplier<SaslAuthenticationFactory> safSupplier = saslAuthenticationFactory != null ? builder.requires(saslAuthenticationFactory) : null;
    final Supplier<SSLContext> scSupplier = sslContext != null ? builder.requires(sslContext): null;
    final Supplier<SocketBindingManager> sbmSupplier = socketBindingManager != null ? builder.requires(socketBindingManager) : null;
    final Supplier<NetworkInterfaceBinding> ibSupplier = builder.requires(networkInterfaceBindingName);
    builder.setInstance(new InjectedNetworkBindingStreamServerService(streamServerConsumer,
            eSupplier, srSupplier, safSupplier, scSupplier, sbmSupplier, ibSupplier, connectorPropertiesOptionMap, port));
    builder.install();
}
 
Example #9
Source File: LdapRealmDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
    ServiceTarget serviceTarget = context.getServiceTarget();

    String address = context.getCurrentAddressValue();
    ServiceName mainServiceName = MODIFIABLE_SECURITY_REALM_RUNTIME_CAPABILITY.fromBaseCapability(address).getCapabilityServiceName();
    ServiceName aliasServiceName = SECURITY_REALM_RUNTIME_CAPABILITY.fromBaseCapability(address).getCapabilityServiceName();

    final LdapSecurityRealmBuilder builder = LdapSecurityRealmBuilder.builder();

    if (DIRECT_VERIFICATION.resolveModelAttribute(context, model).asBoolean()) {
        boolean allowBlankPassword = ALLOW_BLANK_PASSWORD.resolveModelAttribute(context, model).asBoolean();
        builder.addDirectEvidenceVerification(allowBlankPassword);
    }

    TrivialService<SecurityRealm> ldapRealmService = new TrivialService<>(builder::build);
    ServiceBuilder<SecurityRealm> serviceBuilder = serviceTarget.addService(mainServiceName, ldapRealmService)
            .addAliases(aliasServiceName);

    commonDependencies(serviceBuilder);

    configureIdentityMapping(context, model, builder);
    configureDirContext(context, model, builder, serviceBuilder);

    serviceBuilder.setInitialMode(ServiceController.Mode.ACTIVE).install();
}
 
Example #10
Source File: SecurityRealmAddHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Supplier<CallbackHandlerService> addLocalService(OperationContext context, ModelNode local, String realmName, ServiceTarget serviceTarget,
                             ServiceBuilder<?> realmBuilder) 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;
    node = LocalAuthenticationResourceDefinition.SKIP_GROUP_LOADING.resolveModelAttribute(context, local);
    boolean skipGroupLoading = node.asBoolean();

    final ServiceBuilder<?> builder = serviceTarget.addService(localServiceName);
    final Consumer<CallbackHandlerService> chsConsumer = builder.provides(localServiceName);
    builder.setInstance(new LocalCallbackHandlerService(chsConsumer, defaultUser, allowedUsers, skipGroupLoading));
    builder.setInitialMode(ON_DEMAND);
    builder.install();

    return CallbackHandlerService.ServiceUtil.requires(realmBuilder, localServiceName);
}
 
Example #11
Source File: RoleDecoderDefinitions.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model)
        throws OperationFailedException {
    ServiceTarget serviceTarget = context.getServiceTarget();
    RuntimeCapability<Void> runtimeCapability = ROLE_DECODER_RUNTIME_CAPABILITY.fromBaseCapability(context.getCurrentAddressValue());
    ServiceName roleDecoderName = runtimeCapability.getCapabilityServiceName(RoleDecoder.class);

    final String attribute = ATTRIBUTE.resolveModelAttribute(context, model).asString();
    TrivialService<RoleDecoder> roleDecoderService = new TrivialService<RoleDecoder>(() -> RoleDecoder.simple(attribute));

    ServiceBuilder<RoleDecoder> roleDecoderBuilderBuilder = serviceTarget.addService(roleDecoderName, roleDecoderService);

    commonDependencies(roleDecoderBuilderBuilder)
        .setInitialMode(Mode.LAZY)
        .install();
}
 
Example #12
Source File: RoleDecoderDefinitions.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model)
        throws OperationFailedException {
    ServiceTarget serviceTarget = context.getServiceTarget();
    RuntimeCapability<Void> runtimeCapability = ROLE_DECODER_RUNTIME_CAPABILITY.fromBaseCapability(context.getCurrentAddressValue());
    ServiceName roleDecoderName = runtimeCapability.getCapabilityServiceName(RoleDecoder.class);
    final String sourceAddress = SOURCE_ADDRESS.resolveModelAttribute(context, model).asStringOrNull();
    final String pattern = PATTERN.resolveModelAttribute(context, model).asStringOrNull();
    final List<String> roles = ROLES.unwrap(context, model);

    TrivialService<RoleDecoder> roleDecoderService;
    // one of 'source-address' or 'pattern' must be specified
    if (sourceAddress != null) {
        roleDecoderService = new TrivialService<>(() -> new SourceAddressRoleDecoder(sourceAddress, Roles.fromSet(new HashSet<>(roles))));
    } else {
        roleDecoderService = new TrivialService<>(() -> new SourceAddressRoleDecoder(Pattern.compile(pattern), Roles.fromSet(new HashSet<>(roles))));
    }

    ServiceBuilder<RoleDecoder> roleDecoderBuilderBuilder = serviceTarget.addService(roleDecoderName, roleDecoderService);

    commonDependencies(roleDecoderBuilderBuilder)
            .setInitialMode(Mode.LAZY)
            .install();
}
 
Example #13
Source File: RemotingHttpUpgradeService.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void installServices(final OperationContext context, final String remotingConnectorName,
                                   final String httpConnectorName, final ServiceName endpointName,
                                   final OptionMap connectorPropertiesOptionMap, final String securityRealm,
                                   final String saslAuthenticationFactory) {
    final ServiceTarget serviceTarget = context.getServiceTarget();
    final ServiceName serviceName = UPGRADE_SERVICE_NAME.append(remotingConnectorName);
    final ServiceBuilder<?> sb = serviceTarget.addService(serviceName);
    final Consumer<RemotingHttpUpgradeService> serviceConsumer = sb.provides(serviceName);
    final Supplier<ChannelUpgradeHandler> urSupplier = sb.requires(HTTP_UPGRADE_REGISTRY.append(httpConnectorName));
    final Supplier<ListenerRegistry> lrSupplier = sb.requires(RemotingServices.HTTP_LISTENER_REGISTRY);
    final Supplier<Endpoint> eSupplier = sb.requires(endpointName);
    final Supplier<org.jboss.as.domain.management.SecurityRealm> srSupplier = securityRealm != null ? sb.requires(org.jboss.as.domain.management.SecurityRealm.ServiceUtil.createServiceName(securityRealm)) : null;
    final Supplier<SaslAuthenticationFactory> safSupplier = saslAuthenticationFactory != null ? sb.requires(context.getCapabilityServiceName(SASL_AUTHENTICATION_FACTORY_CAPABILITY, saslAuthenticationFactory, SaslAuthenticationFactory.class)) : null;
    sb.setInstance(new RemotingHttpUpgradeService(serviceConsumer, urSupplier, lrSupplier, eSupplier, srSupplier, safSupplier, httpConnectorName, endpointName.getSimpleName(), connectorPropertiesOptionMap));
    sb.setInitialMode(ServiceController.Mode.PASSIVE);
    sb.install();
}
 
Example #14
Source File: RemotingServices.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void installConnectorServicesForSocketBinding(final ServiceTarget serviceTarget,
                                                            final ServiceName endpointName,
                                                            final String connectorName,
                                                            final ServiceName socketBindingName,
                                                            final OptionMap connectorPropertiesOptionMap,
                                                            final ServiceName securityRealm,
                                                            final ServiceName saslAuthenticationFactory,
                                                            final ServiceName sslContext,
                                                            final ServiceName socketBindingManager) {
    final ServiceName serviceName = serverServiceName(connectorName);
    final ServiceBuilder<?> builder = serviceTarget.addService(serviceName);
    final Consumer<AcceptingChannel<StreamConnection>> streamServerConsumer = builder.provides(serviceName);
    final Supplier<Endpoint> eSupplier = builder.requires(endpointName);
    final Supplier<SecurityRealm> srSupplier = securityRealm != null ? builder.requires(securityRealm) : null;
    final Supplier<SaslAuthenticationFactory> safSupplier = saslAuthenticationFactory != null ? builder.requires(saslAuthenticationFactory) : null;
    final Supplier<SSLContext> scSupplier = sslContext != null ? builder.requires(sslContext) : null;
    final Supplier<SocketBindingManager> sbmSupplier = builder.requires(socketBindingManager);
    final Supplier<SocketBinding> sbSupplier = builder.requires(socketBindingName);
    builder.setInstance(new InjectedSocketBindingStreamServerService(streamServerConsumer,
            eSupplier, srSupplier, safSupplier, scSupplier, sbmSupplier, sbSupplier, connectorPropertiesOptionMap));
    builder.install();
}
 
Example #15
Source File: ContentCleanerService.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void addServiceOnHostController(final ServiceTarget serviceTarget, final ServiceName hostControllerServiceName, final ServiceName clientFactoryServiceName,
                                              final ServiceName hostControllerExecutorServiceName, final ServiceName scheduledExecutorServiceName) {
    final ServiceBuilder<?> builder = serviceTarget.addService(SERVICE_NAME);
    final Supplier<ModelControllerClientFactory> mccfSupplier = builder.requires(clientFactoryServiceName);
    final Supplier<ProcessStateNotifier> cpsnSupplier = builder.requires(ControlledProcessStateService.INTERNAL_SERVICE_NAME);
    final Supplier<ScheduledExecutorService> sesSupplier = builder.requires(scheduledExecutorServiceName);
    final Supplier<ExecutorService> esSupplier = builder.requires(hostControllerExecutorServiceName);
    builder.setInstance(new ContentCleanerService(false, mccfSupplier, cpsnSupplier, sesSupplier, esSupplier));
    builder.install();
}
 
Example #16
Source File: ServerPathManagerService.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static ServiceController<?> addService(ServiceTarget serviceTarget, ServerPathManagerService service, ServerEnvironment serverEnvironment) {
    ServiceBuilder<?> serviceBuilder = serviceTarget.addService(AbstractControllerService.PATH_MANAGER_CAPABILITY.getCapabilityServiceName(), service).addAliases(SERVICE_NAME);

    // Add environment paths - registering the actual capabilities
    addAbsolutePath(service, serviceTarget, ServerEnvironment.HOME_DIR, serverEnvironment.getHomeDir());
    addAbsolutePath(service, serviceTarget, ServerEnvironment.SERVER_BASE_DIR, serverEnvironment.getServerBaseDir());
    addAbsolutePath(service, serviceTarget, ServerEnvironment.SERVER_CONFIG_DIR, serverEnvironment.getServerConfigurationDir());
    addAbsolutePath(service, serviceTarget, ServerEnvironment.SERVER_DATA_DIR, serverEnvironment.getServerDataDir());
    addAbsolutePath(service, serviceTarget, ServerEnvironment.SERVER_LOG_DIR, serverEnvironment.getServerLogDir());
    addAbsolutePath(service, serviceTarget, ServerEnvironment.SERVER_TEMP_DIR, serverEnvironment.getServerTempDir());
    addAbsolutePath(service, serviceTarget, ServerEnvironment.CONTROLLER_TEMP_DIR, serverEnvironment.getControllerTempDir());

    // Add system paths - registering the actual capabilities
    service.addHardcodedAbsolutePath(serviceTarget, "user.dir", System.getProperty("user.dir"));
    service.addHardcodedAbsolutePath(serviceTarget, "user.home", System.getProperty("user.home"));
    service.addHardcodedAbsolutePath(serviceTarget, "java.home", System.getProperty("java.home"));

    // In the domain mode add a few more paths - registering the actual capabilities
    if(serverEnvironment.getLaunchType() == ServerEnvironment.LaunchType.DOMAIN) {
        if(serverEnvironment.getDomainBaseDir() != null) {
            service.addHardcodedAbsolutePath(serviceTarget, ServerEnvironment.DOMAIN_BASE_DIR, serverEnvironment.getDomainBaseDir().getAbsolutePath());
        }
        if(serverEnvironment.getDomainConfigurationDir() != null) {
            service.addHardcodedAbsolutePath(serviceTarget, ServerEnvironment.DOMAIN_CONFIG_DIR, serverEnvironment.getDomainConfigurationDir().getAbsolutePath());
        }
    }

    return serviceBuilder.install();
}
 
Example #17
Source File: ModuleLoadService.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static ServiceName install(final ServiceTarget target, final ModuleIdentifier identifier, ModuleLoadService service) {
    final ServiceName serviceName = ServiceModuleLoader.moduleServiceName(identifier);
    final ServiceBuilder<Module> builder = target.addService(serviceName, service);

    builder.addDependency(Services.JBOSS_SERVICE_MODULE_LOADER, ServiceModuleLoader.class, service.getServiceModuleLoader());
    builder.addDependency(ServiceModuleLoader.moduleSpecServiceName(identifier), ModuleDefinition.class, service.getModuleDefinitionInjectedValue());
    builder.requires(ServiceModuleLoader.moduleResolvedServiceName(identifier)); //don't attempt to load until all dependent module specs are up, even transitive ones
    builder.setInitialMode(Mode.ON_DEMAND);

    builder.install();
    return serviceName;
}
 
Example #18
Source File: RemotingServices.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void installRemotingManagementEndpoint(final ServiceTarget serviceTarget, final ServiceName endpointName,
                                                     final String hostName, final EndpointService.EndpointType type, final OptionMap options) {
    final ServiceBuilder<?> builder = serviceTarget.addService(endpointName);
    final Consumer<Endpoint> endpointConsumer = builder.provides(endpointName);
    final Supplier<XnioWorker> workerSupplier = builder.requires(ServiceName.JBOSS.append("serverManagement", "controller", "management", "worker"));
    builder.setInstance(new EndpointService(endpointConsumer, workerSupplier, hostName, type, options));
    builder.install();
}
 
Example #19
Source File: EvidenceDecoderDefinitions.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
static ResourceDefinition getX509SubjectAltNameEvidenceDecoderDefinition() {
    final AttributeDefinition[] attributes = new AttributeDefinition[] { ALT_NAME_TYPE, SEGMENT };
    AbstractAddStepHandler add = new TrivialAddHandler<EvidenceDecoder>(EvidenceDecoder.class, attributes, EVIDENCE_DECODER_RUNTIME_CAPABILITY) {

        @Override
        protected ValueSupplier<EvidenceDecoder> getValueSupplier(ServiceBuilder<EvidenceDecoder> serviceBuilder,
                                                                       OperationContext context, ModelNode model) throws OperationFailedException {
            final String  altNameType = ALT_NAME_TYPE.resolveModelAttribute(context, model).asString();
            final int segment  = SEGMENT.resolveModelAttribute(context, model).asInt();
            return () -> new X509SubjectAltNameEvidenceDecoder(SubjectAltNameType.fromName(altNameType).getType(), segment);
        }
    };
    return new TrivialResourceDefinition(X509_SUBJECT_ALT_NAME_EVIDENCE_DECODER, add, attributes, EVIDENCE_DECODER_RUNTIME_CAPABILITY);
}
 
Example #20
Source File: AuthenticationFactoryDefinitions.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void injectRealmMapper(SimpleAttributeDefinition realmMapperAttribute, ServiceBuilder<?> serviceBuilder, OperationContext context, ModelNode model, Injector<RealmMapper> realmMapperInjector) throws OperationFailedException {
    String realmMapper = realmMapperAttribute.resolveModelAttribute(context, model).asStringOrNull();
    if (realmMapper != null) {
        serviceBuilder.addDependency(context.getCapabilityServiceName(
                buildDynamicCapabilityName(REALM_MAPPER_CAPABILITY, realmMapper), RealmMapper.class),
                RealmMapper.class, realmMapperInjector);
    }
}
 
Example #21
Source File: AuthenticationFactoryDefinitions.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void injectPrincipalTransformer(SimpleAttributeDefinition principalTransformerAttribute, ServiceBuilder<?> serviceBuilder, OperationContext context, ModelNode model, Injector<PrincipalTransformer> principalTransformer) throws OperationFailedException {
    String principalTransformerName = principalTransformerAttribute.resolveModelAttribute(context, model).asStringOrNull();
    if (principalTransformerName != null) {
        serviceBuilder.addDependency(context.getCapabilityServiceName(
                buildDynamicCapabilityName(PRINCIPAL_TRANSFORMER_CAPABILITY, principalTransformerName), PrincipalTransformer.class),
                PrincipalTransformer.class, principalTransformer);
    }
}
 
Example #22
Source File: PermissionMapperDefinitions.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
static ResourceDefinition getConstantPermissionMapper() {
    final AttributeDefinition[] attributes = new AttributeDefinition[] { PERMISSIONS, PERMISSION_SETS };
    TrivialAddHandler<PermissionMapper>  add = new TrivialAddHandler<PermissionMapper>(PermissionMapper.class, attributes, PERMISSION_MAPPER_RUNTIME_CAPABILITY) {

        @Override
        protected ValueSupplier<PermissionMapper> getValueSupplier(ServiceBuilder<PermissionMapper> serviceBuilder,
                                                                   OperationContext context, ModelNode model) throws OperationFailedException {

            List<Permission> permissions = new ArrayList<>();
            if (model.hasDefined(ElytronDescriptionConstants.PERMISSIONS)) {
                for (ModelNode permission : model.require(ElytronDescriptionConstants.PERMISSIONS).asList()) {
                    permissions.add(new Permission(CLASS_NAME.resolveModelAttribute(context, permission).asString(),
                            MODULE.resolveModelAttribute(context, permission).asStringOrNull(),
                            TARGET_NAME.resolveModelAttribute(context, permission).asStringOrNull(),
                            ACTION.resolveModelAttribute(context, permission).asStringOrNull()));
                }
            }

            List<InjectedValue<Permissions>> permissionSetInjectors = new ArrayList<>();
            if (model.hasDefined(ElytronDescriptionConstants.PERMISSION_SETS)) {
                for (ModelNode permissionSet : model.require(ElytronDescriptionConstants.PERMISSION_SETS).asList()) {
                    InjectedValue<Permissions> permissionSetInjector = new InjectedValue<>();
                    String permissionSetName = PERMISSION_SET_NAME.resolveModelAttribute(context, permissionSet).asString();
                    String runtimeCapability = RuntimeCapability.buildDynamicCapabilityName(PERMISSION_SET_CAPABILITY, permissionSetName);
                    ServiceName permissionSetServiceName = context.getCapabilityServiceName(runtimeCapability, Permissions.class);
                    serviceBuilder.addDependency(permissionSetServiceName, Permissions.class, permissionSetInjector);
                    permissionSetInjectors.add(permissionSetInjector);
                }
            }

            return () -> createConstantPermissionMapper(permissions, permissionSetInjectors);
        }
    };

    return new TrivialResourceDefinition(ElytronDescriptionConstants.CONSTANT_PERMISSION_MAPPER, add, attributes, PERMISSION_MAPPER_RUNTIME_CAPABILITY);
}
 
Example #23
Source File: RemotingSubsystemTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private AdditionalInitialization createRuntimeAdditionalInitialization() {
    return new AdditionalInitialization() {
        @Override
        protected void setupController(ControllerInitializer controllerInitializer) {
            controllerInitializer.addSocketBinding("remoting", 27258);
            controllerInitializer.addRemoteOutboundSocketBinding("dummy-outbound-socket", "localhost", 6799);
            controllerInitializer.addRemoteOutboundSocketBinding("other-outbound-socket", "localhost", 1234);
        }

        @Override
        protected void addExtraServices(ServiceTarget target) {
            //Needed for initialization of the RealmAuthenticationProviderService
            AbsolutePathService.addService(ServerEnvironment.CONTROLLER_TEMP_DIR, new File("target/temp" + System.currentTimeMillis()).getAbsolutePath(), target);
            ServiceBuilder<?> builder = target.addService(IOServices.WORKER.append("default"));
            Consumer<XnioWorker> workerConsumer = builder.provides(IOServices.WORKER.append("default"));
            builder.setInstance(new WorkerService(workerConsumer, () -> Executors.newFixedThreadPool(1), Xnio.getInstance().createWorkerBuilder().setWorkerIoThreads(2)));
            builder.setInitialMode(ServiceController.Mode.ON_DEMAND);
            builder.install();

            builder = target.addService(IOServices.WORKER.append("default-remoting"));
            workerConsumer = builder.provides(IOServices.WORKER.append("default-remoting"));
            builder.setInstance(new WorkerService(workerConsumer, () -> Executors.newFixedThreadPool(1), Xnio.getInstance().createWorkerBuilder().setWorkerIoThreads(2)));
            builder.setInitialMode(ServiceController.Mode.ON_DEMAND);
            builder.install();            }

        @Override
        protected void initializeExtraSubystemsAndModel(ExtensionRegistry extensionRegistry, Resource rootResource, ManagementResourceRegistration rootRegistration, RuntimeCapabilityRegistry capabilityRegistry) {
            super.initializeExtraSubystemsAndModel(extensionRegistry, rootResource, rootRegistration, capabilityRegistry);
            Map<String, Class> capabilities = new HashMap<>();
            capabilities.put(buildDynamicCapabilityName(IO_WORKER_CAPABILITY_NAME,
                    RemotingSubsystemRootResource.WORKER.getDefaultValue().asString()), XnioWorker.class);
            capabilities.put(buildDynamicCapabilityName(IO_WORKER_CAPABILITY_NAME,
                    "default-remoting"), XnioWorker.class);
            AdditionalInitialization.registerServiceCapabilities(capabilityRegistry, capabilities);
        }
    };
}
 
Example #24
Source File: Seam2Processor.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Lookup Seam integration resource loader.
 * @return the Seam integration resource loader
 * @throws DeploymentUnitProcessingException for any error
 */
protected synchronized ResourceRoot getSeamIntResourceRoot() throws DeploymentUnitProcessingException {
    try {
        if (seamIntResourceRoot == null) {
            final ModuleLoader moduleLoader = Module.getBootModuleLoader();
            Module extModule = moduleLoader.loadModule(EXT_CONTENT_MODULE);
            URL url = extModule.getExportedResource(SEAM_INT_JAR);
            if (url == null)
                throw ServerLogger.ROOT_LOGGER.noSeamIntegrationJarPresent(extModule);

            File file = new File(url.toURI());
            VirtualFile vf = VFS.getChild(file.toURI());
            final Closeable mountHandle = VFS.mountZip(file, vf, TempFileProviderService.provider());
            Service<Closeable> mountHandleService = new Service<Closeable>() {
                public void start(StartContext startContext) throws StartException {
                }

                public void stop(StopContext stopContext) {
                    VFSUtils.safeClose(mountHandle);
                }

                public Closeable getValue() throws IllegalStateException, IllegalArgumentException {
                    return mountHandle;
                }
            };
            ServiceBuilder<Closeable> builder = serviceTarget.addService(ServiceName.JBOSS.append(SEAM_INT_JAR),
                    mountHandleService);
            builder.setInitialMode(ServiceController.Mode.ACTIVE).install();
            serviceTarget = null; // our cleanup service install work is done

            MountHandle dummy = MountHandle.create(null); // actual close is done by the MSC service above
            seamIntResourceRoot = new ResourceRoot(vf, dummy);
        }
        return seamIntResourceRoot;
    } catch (Exception e) {
        throw new DeploymentUnitProcessingException(e);
    }
}
 
Example #25
Source File: SecurityRealmAddHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Supplier<CallbackHandlerService> addKerberosService(OperationContext context, ModelNode kerberos, String realmName, ServiceTarget serviceTarget,
        ServiceBuilder<?> realmBuilder) throws OperationFailedException {
    final ServiceName kerberosServiceName = KerberosCallbackHandler.ServiceUtil.createServiceName(realmName);
    final boolean removeRealm = KerberosAuthenticationResourceDefinition.REMOVE_REALM.resolveModelAttribute(context, kerberos).asBoolean();
    final ServiceBuilder<?> builder = serviceTarget.addService(kerberosServiceName);
    final Consumer<CallbackHandlerService> chsConsumer = builder.provides(kerberosServiceName);
    builder.setInstance(new KerberosCallbackHandler(chsConsumer, removeRealm));
    builder.setInitialMode(ON_DEMAND);
    builder.install();

    return CallbackHandlerService.ServiceUtil.requires(realmBuilder, kerberosServiceName);
}
 
Example #26
Source File: AbstractControllerTestBase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Before
public void setupController() throws InterruptedException {
    container = ServiceContainer.Factory.create("test");
    ServiceTarget target = container.subTarget();
    ModelControllerService svc = new ModelControllerService(processType, getAuditLogger());
    ServiceBuilder<ModelController> builder = target.addService(ServiceName.of("ModelController"), svc);
    builder.install();
    svc.awaitStartup(30, TimeUnit.SECONDS);
    controller = svc.getValue();
    //ModelNode setup = Util.getEmptyOperation("setup", new ModelNode());
    //controller.execute(setup, null, null, null);
}
 
Example #27
Source File: PrincipalTransformerDefinitions.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
static ResourceDefinition getConstantPrincipalTransformerDefinition() {
    final AttributeDefinition[] attributes = new AttributeDefinition[] { CONSTANT };
    AbstractAddStepHandler add = new TrivialAddHandler<PrincipalTransformer>(PrincipalTransformer.class, attributes, PRINCIPAL_TRANSFORMER_RUNTIME_CAPABILITY) {

        @Override
        protected ValueSupplier<PrincipalTransformer> getValueSupplier(ServiceBuilder<PrincipalTransformer> serviceBuilder,
                OperationContext context, ModelNode model) throws OperationFailedException {
            final Principal principal = new NamePrincipal(CONSTANT.resolveModelAttribute(context, model).asString());

            return () -> p -> principal;
        }
    };

    return new TrivialResourceDefinition(CONSTANT_PRINCIPAL_TRANSFORMER, add, attributes, PRINCIPAL_TRANSFORMER_RUNTIME_CAPABILITY);
}
 
Example #28
Source File: ExternalModuleService.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void addService(final ServiceTarget serviceTarget, final ServiceName externalModuleServiceName) {
    final ServiceBuilder<?> serviceBuilder = serviceTarget.addService(externalModuleServiceName);
    final Consumer<ExternalModuleService> provides = serviceBuilder.provides(Services.JBOSS_EXTERNAL_MODULE_SERVICE);

    serviceBuilder.setInstance(new ExternalModuleService(provides))
            .install();
}
 
Example #29
Source File: HttpServerDefinitions.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
static ResourceDefinition getProviderHttpServerMechanismFactoryDefinition() {
    AttributeDefinition[] attributes = new AttributeDefinition[] { PROVIDERS };
    AbstractAddStepHandler add = new TrivialAddHandler<HttpServerAuthenticationMechanismFactory>(HttpServerAuthenticationMechanismFactory.class, attributes, HTTP_SERVER_MECHANISM_FACTORY_RUNTIME_CAPABILITY) {

        @Override
        protected ValueSupplier<HttpServerAuthenticationMechanismFactory> getValueSupplier(
                ServiceBuilder<HttpServerAuthenticationMechanismFactory> serviceBuilder, OperationContext context,
                ModelNode model) throws OperationFailedException {

            String providers = PROVIDERS.resolveModelAttribute(context, model).asStringOrNull();
            final Supplier<Provider[]> providerSupplier;
            if (providers != null) {
                final InjectedValue<Provider[]> providersInjector = new InjectedValue<Provider[]>();
                serviceBuilder.addDependency(context.getCapabilityServiceName(
                        buildDynamicCapabilityName(PROVIDERS_CAPABILITY, providers), Provider[].class),
                        Provider[].class, providersInjector);
                providerSupplier = providersInjector::getValue;
            } else {
                providerSupplier = Security::getProviders;
            }

            Predicate<Provider.Service> serviceFilter = (Provider.Service s) -> HttpServerAuthenticationMechanismFactory.class.getSimpleName().equals(s.getType());

            return () -> {
                final Provider[] actualProviders = providerSupplier.get();
                if ( findProviderService(actualProviders, serviceFilter) == null ) {
                    throw ROOT_LOGGER.noSuitableProvider(HttpServerAuthenticationMechanismFactory.class.getSimpleName());
                }
                return new SetMechanismInformationMechanismFactory(new SecurityProviderServerMechanismFactory(actualProviders));
            };
        }

    };

    return wrapFactory(new TrivialResourceDefinition(ElytronDescriptionConstants.PROVIDER_HTTP_SERVER_MECHANISM_FACTORY, add,
            attributes, HTTP_SERVER_MECHANISM_FACTORY_RUNTIME_CAPABILITY));
}
 
Example #30
Source File: CertificateAuthorityAccountDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected void performRuntime(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
    ModelNode model = resource.getModel();
    String certificateAuthorityName = CERTIFICATE_AUTHORITY.resolveModelAttribute(context, model).asString();
    final String alias = ALIAS.resolveModelAttribute(context, model).asString();
    final String keyStoreName = KEY_STORE.resolveModelAttribute(context, model).asString();
    ExceptionSupplier<CredentialSource, Exception> credentialSourceSupplier = null;
    if (CREDENTIAL_REFERENCE.resolveModelAttribute(context, operation).isDefined()) {
        credentialSourceSupplier = CredentialReference.getCredentialSourceSupplier(context, CREDENTIAL_REFERENCE, operation, null);
    }
    final List<ModelNode> contactUrls = CONTACT_URLS.resolveModelAttribute(context, model).asListOrEmpty();
    final List<String> contactUrlsList = new ArrayList<>(contactUrls.size());
    for (ModelNode contactUrl : contactUrls) {
        contactUrlsList.add(contactUrl.asString());
    }

    AcmeAccountService acmeAccountService = new AcmeAccountService(certificateAuthorityName, contactUrlsList, alias, keyStoreName);
    ServiceTarget serviceTarget = context.getServiceTarget();
    RuntimeCapability<Void> certificateAuthorityAccountRuntimeCapability = CERTIFICATE_AUTHORITY_ACCOUNT_RUNTIME_CAPABILITY.fromBaseCapability(context.getCurrentAddressValue());
    ServiceName acmeAccountServiceName = certificateAuthorityAccountRuntimeCapability.getCapabilityServiceName(AcmeAccount.class);
    ServiceBuilder<AcmeAccount> acmeAccountServiceBuilder = serviceTarget.addService(acmeAccountServiceName, acmeAccountService).setInitialMode(ServiceController.Mode.ACTIVE);
    acmeAccountService.getCredentialSourceSupplierInjector().inject(credentialSourceSupplier);

    String keyStoreCapabilityName = RuntimeCapability.buildDynamicCapabilityName(KEY_STORE_CAPABILITY, keyStoreName);
    acmeAccountServiceBuilder.addDependency(context.getCapabilityServiceName(keyStoreCapabilityName, KeyStore.class), KeyStore.class, acmeAccountService.getKeyStoreInjector());
    if (certificateAuthorityName.equalsIgnoreCase(CertificateAuthority.LETS_ENCRYPT.getName())) {
        commonRequirements(acmeAccountServiceBuilder).install();
    } else {
        acmeAccountServiceBuilder.requires(CERTIFICATE_AUTHORITY_RUNTIME_CAPABILITY.getCapabilityServiceName(certificateAuthorityName));
        commonRequirements(acmeAccountServiceBuilder).install();
    }
}