@Test
  public void testModuleDelegatesToFramework() throws Exception {
    ModuleIdentifier identifierF = ModuleIdentifier.create("framework");
    ModuleSpec.Builder specBuilderF = ModuleSpec.build(identifierF);
    PathFilter importFilter = getSystemFilter();
    PathFilter exportFilter = PathFilters.acceptAll();
    specBuilderF.addDependency(
        DependencySpec.createSystemDependencySpec(importFilter, exportFilter, getSystemPaths()));
    importFilter = PathFilters.in(getFrameworkPaths());
    exportFilter = PathFilters.acceptAll();
    FrameworkLocalLoader localLoader = new FrameworkLocalLoader(Bundle.class.getClassLoader());
    specBuilderF.addDependency(
        DependencySpec.createLocalDependencySpec(
            importFilter, exportFilter, localLoader, getFrameworkPaths()));
    addModuleSpec(specBuilderF.create());

    ModuleIdentifier identifierA = ModuleIdentifier.create("moduleA");
    ModuleSpec.Builder specBuilderA = ModuleSpec.build(identifierA);
    VirtualFileResourceLoader resourceLoaderA = new VirtualFileResourceLoader(virtualFileA);
    specBuilderA.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(resourceLoaderA));
    specBuilderA.addDependency(DependencySpec.createModuleDependencySpec(identifierF));
    specBuilderA.addDependency(DependencySpec.createLocalDependencySpec());
    addModuleSpec(specBuilderA.create());

    assertLoadClass(identifierA, "org.osgi.framework.Bundle");
    assertLoadClass(identifierA, "javax.security.auth.x500.X500Principal");
  }
/**
 * Deployment processor which adds module dependencies for JAXR.
 *
 * @author [email protected]
 * @since 09-Dec-2011
 */
public class JAXRDependencyProcessor implements DeploymentUnitProcessor {

  public static ModuleIdentifier APACHE_SCOUT = ModuleIdentifier.create("org.apache.juddi.scout");
  public static ModuleIdentifier JBOSS_JAXR = ModuleIdentifier.create("org.jboss.as.jaxr");

  public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    final ModuleSpecification moduleSpecification =
        deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);

    final ModuleLoader moduleLoader = Module.getBootModuleLoader();
    addDependency(moduleSpecification, moduleLoader, APACHE_SCOUT);
    addDependency(moduleSpecification, moduleLoader, JBOSS_JAXR);
  }

  private void addDependency(
      ModuleSpecification moduleSpecification,
      ModuleLoader moduleLoader,
      ModuleIdentifier moduleIdentifier) {
    moduleSpecification.addSystemDependency(
        new ModuleDependency(moduleLoader, moduleIdentifier, false, false, true, false));
  }

  @Override
  public void undeploy(DeploymentUnit context) {}
}
/** @author Stan Silvert [email protected] (C) 2013 Red Hat Inc. */
public abstract class KeycloakDependencyProcessor implements DeploymentUnitProcessor {

  private static final ModuleIdentifier KEYCLOAK_JBOSS_CORE_ADAPTER =
      ModuleIdentifier.create("org.keycloak.keycloak-jboss-adapter-core");
  private static final ModuleIdentifier KEYCLOAK_CORE_ADAPTER =
      ModuleIdentifier.create("org.keycloak.keycloak-adapter-core");
  private static final ModuleIdentifier KEYCLOAK_CORE =
      ModuleIdentifier.create("org.keycloak.keycloak-core");
  private static final ModuleIdentifier KEYCLOAK_COMMON =
      ModuleIdentifier.create("org.keycloak.keycloak-common");

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

    if (!KeycloakAdapterConfigService.getInstance().isSecureDeployment(deploymentUnit)) {
      WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
      if (warMetaData == null) {
        return;
      }
      JBossWebMetaData webMetaData = warMetaData.getMergedJBossWebMetaData();
      if (webMetaData == null) {
        return;
      }
      LoginConfigMetaData loginConfig = webMetaData.getLoginConfig();
      if (loginConfig == null) return;
      if (loginConfig.getAuthMethod() == null) return;
      if (!loginConfig.getAuthMethod().equals("KEYCLOAK")) return;
    }

    final ModuleSpecification moduleSpecification =
        deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
    final ModuleLoader moduleLoader = Module.getBootModuleLoader();
    addCommonModules(moduleSpecification, moduleLoader);
    addPlatformSpecificModules(moduleSpecification, moduleLoader);
  }

  private void addCommonModules(
      ModuleSpecification moduleSpecification, ModuleLoader moduleLoader) {
    // ModuleDependency(ModuleLoader moduleLoader, ModuleIdentifier identifier, boolean optional,
    // boolean export, boolean importServices, boolean userSpecified)
    moduleSpecification.addSystemDependency(
        new ModuleDependency(
            moduleLoader, KEYCLOAK_JBOSS_CORE_ADAPTER, false, false, false, false));
    moduleSpecification.addSystemDependency(
        new ModuleDependency(moduleLoader, KEYCLOAK_CORE_ADAPTER, false, false, false, false));
    moduleSpecification.addSystemDependency(
        new ModuleDependency(moduleLoader, KEYCLOAK_CORE, false, false, false, false));
    moduleSpecification.addSystemDependency(
        new ModuleDependency(moduleLoader, KEYCLOAK_COMMON, false, false, false, false));
  }

  protected abstract void addPlatformSpecificModules(
      ModuleSpecification moduleSpecification, ModuleLoader moduleLoader);

  @Override
  public void undeploy(DeploymentUnit du) {}
}
  /**
   * Loads/caches the persistence provider adapter
   *
   * @param adapterModule may specify the adapter module name (can be null to use noop provider)
   * @return the persistence provider adaptor for the provider class
   * @throws ModuleLoadException
   */
  public static PersistenceProviderAdaptor loadPersistenceAdapterModule(String adapterModule)
      throws ModuleLoadException {
    final ModuleLoader moduleLoader = Module.getBootModuleLoader();

    if (adapterModule == null) {
      return noopAdaptor;
    }

    PersistenceProviderAdaptor persistenceProviderAdaptor = null;

    Module module = moduleLoader.loadModule(ModuleIdentifier.fromString(adapterModule));
    final ServiceLoader<PersistenceProviderAdaptor> serviceLoader =
        module.loadService(PersistenceProviderAdaptor.class);
    if (serviceLoader != null) {
      for (PersistenceProviderAdaptor adaptor : serviceLoader) {
        if (persistenceProviderAdaptor != null) {
          throw MESSAGES.multipleAdapters(adapterModule);
        }
        persistenceProviderAdaptor = adaptor;
        JPA_LOGGER.debugf("loaded persistence provider adapter %s", adapterModule);
      }
      if (persistenceProviderAdaptor != null) {
        persistenceProviderAdaptor.injectJtaManager(JtaManagerImpl.getInstance());
      }
    }
    return persistenceProviderAdaptor;
  }
  private static void setupLoggingSystem(ModuleLoader moduleLoader) {
    final ModuleIdentifier logModuleId = ModuleIdentifier.create(MODULE_ID_LOGMANAGER);
    final Module logModule;
    try {
      logModule = moduleLoader.loadModule(logModuleId);
    } catch (final ModuleLoadException mle) {
      throw EmbeddedLogger.ROOT_LOGGER.moduleLoaderError(mle, MODULE_ID_LOGMANAGER, moduleLoader);
    }

    final ModuleClassLoader logModuleClassLoader = logModule.getClassLoader();
    final ClassLoader tccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
    try {
      WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(logModuleClassLoader);
      WildFlySecurityManager.setPropertyPrivileged(
          SYSPROP_KEY_LOGMANAGER, SYSPROP_VALUE_JBOSS_LOGMANAGER);

      final Class<?> actualLogManagerClass = LogManager.getLogManager().getClass();
      if (actualLogManagerClass == LogManager.class) {
        System.err.println(
            "Cannot not load JBoss LogManager. The LogManager has likely been accessed prior to this initialization.");
      } else {
        Module.setModuleLogger(new JDKModuleLogger());
      }
    } finally {
      // Reset TCCL
      WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(tccl);
    }
  }
  public void start() {
    final Xnio xnio;
    try {
      // Do what org.jboss.as.remoting.XnioUtil does
      xnio =
          Xnio.getInstance(
              null,
              Module.getModuleFromCallerModuleLoader(
                      ModuleIdentifier.fromString("org.jboss.xnio.nio"))
                  .getClassLoader());
    } catch (Exception e) {
      throw new IllegalStateException(e.getLocalizedMessage());
    }
    try {
      // TODO make this configurable
      worker =
          xnio.createWorker(
              OptionMap.builder()
                  .set(Options.WORKER_IO_THREADS, 4)
                  .set(Options.CONNECTION_HIGH_WATER, 1000000)
                  .set(Options.CONNECTION_LOW_WATER, 1000000)
                  .set(Options.WORKER_TASK_CORE_THREADS, 10)
                  .set(Options.WORKER_TASK_MAX_THREADS, 12)
                  .set(Options.TCP_NODELAY, true)
                  .set(Options.CORK, true)
                  .getMap());

      Builder serverOptionsBuilder =
          OptionMap.builder().set(Options.TCP_NODELAY, true).set(Options.REUSE_ADDRESSES, true);
      ChannelListener acceptListener = ChannelListeners.openListenerAdapter(openListener);
      if (httpAddress != null) {
        normalServer =
            worker.createStreamConnectionServer(
                httpAddress, acceptListener, serverOptionsBuilder.getMap());
        normalServer.resumeAccepts();
      }
      if (secureAddress != null) {
        SSLContext sslContext = securityRealm.getSSLContext();
        Set<AuthMechanism> supportedMechanisms =
            securityRealm.getSupportedAuthenticationMechanisms();
        if (supportedMechanisms.contains(AuthMechanism.CLIENT_CERT)) {
          if (supportedMechanisms.contains(AuthMechanism.DIGEST)
              || supportedMechanisms.contains(AuthMechanism.PLAIN)) {
            // Username / Password auth is possible so don't mandate a client certificate.
            serverOptionsBuilder.set(SSL_CLIENT_AUTH_MODE, REQUESTED);
          } else {
            serverOptionsBuilder.set(SSL_CLIENT_AUTH_MODE, REQUIRED);
          }
        }
        OptionMap secureOptions = serverOptionsBuilder.getMap();
        XnioSsl xnioSsl = new JsseXnioSsl(worker.getXnio(), secureOptions, sslContext);
        secureServer =
            xnioSsl.createSslConnectionServer(worker, secureAddress, acceptListener, secureOptions);
        secureServer.resumeAccepts();
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
 @Test
 public void testAccessFromCamelComponentModule() throws Exception {
   ModuleLoader moduleLoader = Module.getCallerModuleLoader();
   ModuleIdentifier modid = ModuleIdentifier.create("org.apache.camel.component");
   ModuleClassLoader classLoader = moduleLoader.loadModule(modid).getClassLoader();
   URL resurl = classLoader.getResource("META-INF/cxf/cxf.xml");
   Assert.assertNotNull("URL not null", resurl);
 }
  private boolean isValidCandidate(String resName, XPackageRequirement pkgreq, Module candidate) {

    if (candidate == null) return false;

    // Skip dynamic loads from this module
    ModuleIdentifier candidateId = candidate.getIdentifier();
    if (candidateId.equals(identifier)) return false;

    log.tracef("Attempt to find path dynamically [%s] in %s ...", resName, candidateId);
    URL resURL = candidate.getExportedResource(resName);
    if (resURL == null) return false;

    log.tracef("Found path [%s] in %s", resName, candidate);
    BundleRevision brev = moduleManager.getBundleRevision(candidateId);
    XPackageCapability candidateCap = getCandidateCapability(brev, pkgreq);
    return (candidateCap != null);
  }
 @Test
 public void testAvailableOnModule() throws Exception {
   ModuleIdentifier identifierA = ModuleIdentifier.create("moduleA");
   ModuleSpec.Builder specBuilderA = ModuleSpec.build(identifierA);
   VirtualFileResourceLoader resourceLoaderA = new VirtualFileResourceLoader(virtualFileA);
   specBuilderA.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(resourceLoaderA));
   specBuilderA.addDependency(DependencySpec.createLocalDependencySpec());
   addModuleSpec(specBuilderA.create());
   assertLoadClass(identifierA, "javax.security.auth.x500.X500Principal", identifierA);
 }
 private static void setupVfsModule(final ModuleLoader moduleLoader) {
   final ModuleIdentifier vfsModuleID = ModuleIdentifier.create(MODULE_ID_VFS);
   final Module vfsModule;
   try {
     vfsModule = moduleLoader.loadModule(vfsModuleID);
   } catch (final ModuleLoadException mle) {
     throw EmbeddedLogger.ROOT_LOGGER.moduleLoaderError(mle, MODULE_ID_VFS, moduleLoader);
   }
   Module.registerURLStreamHandlerFactoryModule(vfsModule);
 }
/** @author Stan Silvert [email protected] (C) 2013 Red Hat Inc. */
public abstract class KeycloakDependencyProcessor implements DeploymentUnitProcessor {

  private static final ModuleIdentifier KEYCLOAK_JBOSS_CORE_ADAPTER =
      ModuleIdentifier.create("org.keycloak.keycloak-jboss-adapter-core");
  private static final ModuleIdentifier KEYCLOAK_CORE_ADAPTER =
      ModuleIdentifier.create("org.keycloak.keycloak-adapter-core");
  private static final ModuleIdentifier KEYCLOAK_CORE =
      ModuleIdentifier.create("org.keycloak.keycloak-core");

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

    // Next phase, need to detect if this is a Keycloak deployment.  If not, don't add the modules.

    final ModuleSpecification moduleSpecification =
        deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
    final ModuleLoader moduleLoader = Module.getBootModuleLoader();
    addCommonModules(moduleSpecification, moduleLoader);
    addPlatformSpecificModules(moduleSpecification, moduleLoader);
  }

  private void addCommonModules(
      ModuleSpecification moduleSpecification, ModuleLoader moduleLoader) {
    // ModuleDependency(ModuleLoader moduleLoader, ModuleIdentifier identifier, boolean optional,
    // boolean export, boolean importServices, boolean userSpecified)
    moduleSpecification.addSystemDependency(
        new ModuleDependency(
            moduleLoader, KEYCLOAK_JBOSS_CORE_ADAPTER, false, false, false, false));
    moduleSpecification.addSystemDependency(
        new ModuleDependency(moduleLoader, KEYCLOAK_CORE_ADAPTER, false, false, false, false));
    moduleSpecification.addSystemDependency(
        new ModuleDependency(moduleLoader, KEYCLOAK_CORE, false, false, false, false));
  }

  protected abstract void addPlatformSpecificModules(
      ModuleSpecification moduleSpecification, ModuleLoader moduleLoader);

  @Override
  public void undeploy(DeploymentUnit du) {}
}
 /** {@inheritDoc} */
 @Override
 protected String installExtension(String module, OperationContext context) {
   try {
     for (Extension extension :
         Module.loadServiceFromCurrent(ModuleIdentifier.fromString(module), Extension.class)) {
       extension.initialize(extensionContext);
     }
     return null;
   } catch (ModuleLoadException e) {
     return e.getLocalizedMessage();
   }
 }
  public static void main(String[] args) throws Exception {

    System.setProperty("swarm.isuberjar", Boolean.TRUE.toString());
    System.setProperty("boot.module.loader", BootModuleLoader.class.getName());

    Module module =
        Module.getBootModuleLoader()
            .loadModule(ModuleIdentifier.create("org.wildfly.swarm.configuration.teiid", "api"));

    Class<?> clazz =
        module.loadModuleClass("org.wildfly.swarm.config.teiid.TranslatorConsumer", false);
    System.out.println(clazz);
  }
Esempio n. 14
0
public class RarConfigProcessor implements DeploymentUnitProcessor {
  public static final long PRIORITY = DeploymentPhases.MODULE_DEPENDENCIES.plus(200L);
  private static ModuleIdentifier JAVAX_ID = ModuleIdentifier.create("javax.resource.api");
  private static ModuleIdentifier LOGGING_ID = ModuleIdentifier.create("org.jboss.logging");
  private static ModuleIdentifier IRON_JACAMAR_ID =
      ModuleIdentifier.create("org.jboss.ironjacamar.api");
  private static ModuleIdentifier IRON_JACAMAR_IMPL_ID =
      ModuleIdentifier.create("org.jboss.ironjacamar.impl");
  private static ModuleIdentifier NAMING_ID = ModuleIdentifier.create("org.jboss.as.naming");
  private static ModuleIdentifier VALIDATION_ID = ModuleIdentifier.create("javax.validation.api");
  private static ModuleIdentifier HIBERNATE_VALIDATOR_ID =
      ModuleIdentifier.create("org.hibernate.validator");
  private static ModuleIdentifier COMMON_CORE_ID = ModuleIdentifier.create("org.jboss.common-core");

  private static ModuleIdentifier SYSTEM_ID = ModuleIdentifier.create("javax.api");

  /**
   * Add dependencies for modules required for ra deployments
   *
   * @param context the deployment unit context
   * @throws DeploymentUnitProcessingException
   */
  public void processDeployment(DeploymentUnitContext context)
      throws DeploymentUnitProcessingException {
    ModuleDependencies.addDependency(
        context, new ModuleConfig.Dependency(JAVAX_ID, true, false, false));
    ModuleDependencies.addDependency(
        context, new ModuleConfig.Dependency(LOGGING_ID, true, false, false));
    ModuleDependencies.addDependency(
        context, new ModuleConfig.Dependency(IRON_JACAMAR_ID, true, false, false));
    ModuleDependencies.addDependency(
        context, new ModuleConfig.Dependency(IRON_JACAMAR_IMPL_ID, true, false, true));
    ModuleDependencies.addDependency(
        context, new ModuleConfig.Dependency(SYSTEM_ID, true, false, false));
    ModuleDependencies.addDependency(
        context, new ModuleConfig.Dependency(NAMING_ID, true, false, false));
    ModuleDependencies.addDependency(
        context, new ModuleConfig.Dependency(VALIDATION_ID, true, false, false));
    ModuleDependencies.addDependency(
        context, new ModuleConfig.Dependency(HIBERNATE_VALIDATOR_ID, true, false, false));
    ModuleDependencies.addDependency(
        context, new ModuleConfig.Dependency(COMMON_CORE_ID, true, false, false));
  }
}
  @Test
  public void testTwoHopDelegation() throws Exception {

    ModuleIdentifier identifierB = ModuleIdentifier.create("moduleB");
    ModuleSpec.Builder specBuilderB = ModuleSpec.build(identifierB);
    PathFilter importFilter = getSystemFilter();
    PathFilter exportFilter = PathFilters.acceptAll();
    specBuilderB.addDependency(
        DependencySpec.createSystemDependencySpec(importFilter, exportFilter, getSystemPaths()));
    addModuleSpec(specBuilderB.create());

    ModuleIdentifier identifierA = ModuleIdentifier.create("moduleA");
    ModuleSpec.Builder specBuilderA = ModuleSpec.build(identifierA);
    VirtualFileResourceLoader resourceLoaderA = new VirtualFileResourceLoader(virtualFileA);
    specBuilderA.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(resourceLoaderA));
    specBuilderA.addDependency(DependencySpec.createModuleDependencySpec(identifierB));
    specBuilderA.addDependency(DependencySpec.createLocalDependencySpec());
    addModuleSpec(specBuilderA.create());

    assertLoadClass(identifierB, "javax.security.auth.x500.X500Principal", null);
    assertLoadClass(identifierA, "javax.security.auth.x500.X500Principal", null);
  }
  /**
   * This method retrieves all security permissions contained within the specified node.
   *
   * @param context the {@link OperationContext} used to resolve the permission attributes.
   * @param node the {@link ModelNode} that might contain security permissions metadata.
   * @return a {@link List} containing the retrieved permissions. They are wrapped as {@link
   *     PermissionFactory} instances.
   * @throws OperationFailedException if an error occurs while retrieving the security permissions.
   */
  protected List<PermissionFactory> retrievePermissionSet(
      final OperationContext context, final ModelNode node) throws OperationFailedException {

    final List<PermissionFactory> permissions = new ArrayList<PermissionFactory>();

    if (node != null && node.hasDefined(PERMISSION)) {
      for (Property property : node.get(PERMISSION).asPropertyList()) {
        ModelNode permissionNode = property.getValue();
        String permissionClass =
            PermissionResourceDefinition.CLASS
                .resolveModelAttribute(context, permissionNode)
                .asString();
        String permissionName = null;
        if (permissionNode.hasDefined(PERMISSION_NAME))
          permissionName =
              PermissionResourceDefinition.NAME
                  .resolveModelAttribute(context, permissionNode)
                  .asString();
        String permissionActions = null;
        if (permissionNode.hasDefined(PERMISSION_ACTIONS))
          permissionActions =
              PermissionResourceDefinition.ACTIONS
                  .resolveModelAttribute(context, permissionNode)
                  .asString();
        String moduleName = null;
        if (permissionNode.hasDefined(PERMISSION_MODULE)) {
          moduleName =
              PermissionResourceDefinition.MODULE
                  .resolveModelAttribute(context, permissionNode)
                  .asString();
        }
        ClassLoader cl = WildFlySecurityManager.getClassLoaderPrivileged(this.getClass());
        if (moduleName != null) {
          try {
            cl =
                Module.getBootModuleLoader()
                    .loadModule(ModuleIdentifier.create(moduleName))
                    .getClassLoader();
          } catch (ModuleLoadException e) {
            throw new OperationFailedException(e);
          }
        }

        permissions.add(
            new LoadedPermissionFactory(cl, permissionClass, permissionName, permissionActions));
      }
    }
    return permissions;
  }
/** @author <a href="mailto:[email protected]">George Gastaldi</a> */
public class AppleScriptClasspathSpec extends AbstractModuleSpecProvider {
  public static final ModuleIdentifier ID = ModuleIdentifier.create("apple.script");

  public static Set<String> paths = Collections.singleton("apple/applescript");

  @Override
  protected ModuleIdentifier getId() {
    return ID;
  }

  @Override
  protected Set<String> getPaths() {
    return paths;
  }
}
  @Test
  public void testAvailableFrameworkModule() throws Exception {
    ModuleIdentifier identifierF = ModuleIdentifier.create("framework");
    ModuleSpec.Builder specBuilderF = ModuleSpec.build(identifierF);
    PathFilter importFilter = PathFilters.in(getFrameworkPaths());
    PathFilter exportFilter = PathFilters.acceptAll();
    FrameworkLocalLoader localLoader = new FrameworkLocalLoader(Bundle.class.getClassLoader());
    specBuilderF.addDependency(
        DependencySpec.createLocalDependencySpec(
            importFilter, exportFilter, localLoader, getFrameworkPaths()));
    addModuleSpec(specBuilderF.create());

    assertLoadClass(identifierF, "org.osgi.framework.Bundle");
    assertLoadClassFail(identifierF, "javax.security.auth.x500.X500Principal");
  }
  public void start() {
    final Xnio xnio;
    try {
      // Do what org.jboss.as.remoting.XnioUtil does
      xnio =
          Xnio.getInstance(
              null,
              Module.getModuleFromCallerModuleLoader(
                      ModuleIdentifier.fromString("org.jboss.xnio.nio"))
                  .getClassLoader());
    } catch (Exception e) {
      throw new IllegalStateException(e.getLocalizedMessage());
    }
    try {
      // TODO make this configurable
      worker =
          xnio.createWorker(
              OptionMap.builder()
                  .set(Options.WORKER_IO_THREADS, 2)
                  .set(Options.WORKER_TASK_CORE_THREADS, 5)
                  .set(Options.WORKER_TASK_MAX_THREADS, 10)
                  .set(Options.TCP_NODELAY, true)
                  .set(Options.CORK, true)
                  .getMap());

      Builder serverOptionsBuilder =
          OptionMap.builder().set(Options.TCP_NODELAY, true).set(Options.REUSE_ADDRESSES, true);
      ChannelListener acceptListener = ChannelListeners.openListenerAdapter(openListener);
      if (httpAddress != null) {
        normalServer =
            worker.createStreamConnectionServer(
                httpAddress, acceptListener, serverOptionsBuilder.getMap());
        normalServer.resumeAccepts();
      }
      if (secureAddress != null) {
        if (sslClientAuthMode != null) {
          serverOptionsBuilder.set(SSL_CLIENT_AUTH_MODE, sslClientAuthMode);
        }
        OptionMap secureOptions = serverOptionsBuilder.getMap();
        XnioSsl xnioSsl = new UndertowXnioSsl(worker.getXnio(), secureOptions, sslContext);
        secureServer =
            xnioSsl.createSslConnectionServer(worker, secureAddress, acceptListener, secureOptions);
        secureServer.resumeAccepts();
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
Esempio n. 20
0
 public void startBridge() throws Exception {
   if (moduleName == null) {
     bridge.start();
   } else {
     ClassLoader oldTccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
     try {
       ModuleIdentifier moduleID = ModuleIdentifier.create(moduleName);
       Module module = Module.getCallerModuleLoader().loadModule(moduleID);
       WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(module.getClassLoader());
       bridge.start();
     } finally {
       WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
     }
   }
   MessagingLogger.MESSAGING_LOGGER.startedService("JMS Bridge", bridgeName);
 }
 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;
 }
  @Test
  public void testNotAvailableOnSystemModule() throws Exception {
    ModuleIdentifier identifierA = ModuleIdentifier.create("moduleA");
    ModuleSpec.Builder specBuilderA = ModuleSpec.build(identifierA);
    VirtualFileResourceLoader resourceLoaderA = new VirtualFileResourceLoader(virtualFileA);
    specBuilderA.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(resourceLoaderA));
    PathFilter importFilter = getSystemFilter();
    PathFilter exportFilter = PathFilters.acceptAll();
    specBuilderA.addDependency(
        DependencySpec.createSystemDependencySpec(importFilter, exportFilter, getSystemPaths()));
    specBuilderA.addDependency(DependencySpec.createLocalDependencySpec());
    addModuleSpec(specBuilderA.create());

    assertLoadClassFail(identifierA, "org.osgi.framework.Bundle");
    assertLoadClass(identifierA, "javax.security.auth.x500.X500Principal");
  }
  private Module getModule(ModelNode moduleNode) {
    Module module;

    if (moduleNode.isDefined()) {
      ModuleLoader moduleLoader = Module.getBootModuleLoader();
      try {
        module = moduleLoader.loadModule(ModuleIdentifier.create(moduleNode.asString()));
      } catch (ModuleLoadException e) {
        throw ROOT_LOGGER.moduleCouldNotLoad(moduleNode.asString(), e);
      }
    } else {
      // fallback to caller module.
      module = Module.getCallerModule();
    }

    return module;
  }
 @Override
 public synchronized void start(final StartContext context) throws StartException {
   final Handler handler;
   final ModuleLoader moduleLoader = Module.forClass(CustomHandlerService.class).getModuleLoader();
   final ModuleIdentifier id = ModuleIdentifier.create(moduleName);
   try {
     final Class<?> handlerClass =
         Class.forName(className, false, moduleLoader.loadModule(id).getClassLoader());
     if (Handler.class.isAssignableFrom(handlerClass)) {
       handler = (Handler) handlerClass.newInstance();
     } else {
       throw new StartException(
           String.format(
               "%s %s is not a valid %s.", CUSTOM_HANDLER, className, Handler.class.getName()));
     }
   } catch (ClassNotFoundException e) {
     throw new StartException(e);
   } catch (ModuleLoadException e) {
     throw new StartException(
         String.format(
             "%s %s is not a valid %s.", CUSTOM_HANDLER, className, Handler.class.getName()),
         e);
   } catch (InstantiationException e) {
     throw new StartException(
         String.format(
             "%s %s is not a valid %s.", CUSTOM_HANDLER, className, Handler.class.getName()),
         e);
   } catch (IllegalAccessException e) {
     throw new StartException(
         String.format(
             "%s %s is not a valid %s.", CUSTOM_HANDLER, className, Handler.class.getName()),
         e);
   }
   formatterSpec.apply(handler);
   if (level != null) handler.setLevel(level);
   try {
     handler.setEncoding(encoding);
   } catch (UnsupportedEncodingException e) {
     throw new StartException(e);
   }
   value = handler;
 }
Esempio n. 25
0
 static ModuleClassLoader getModuleClassLoader(final String moduleSpec)
     throws ModuleLoadException {
   if (System.getSecurityManager() != null) {
     try {
       return AccessController.doPrivileged(
           new PrivilegedExceptionAction<ModuleClassLoader>() {
             public ModuleClassLoader run() throws ModuleLoadException {
               ModuleLoader loader = Module.getCallerModuleLoader();
               ModuleIdentifier identifier = ModuleIdentifier.fromString(moduleSpec);
               return loader.loadModule(identifier).getClassLoader();
             }
           });
     } catch (PrivilegedActionException pae) {
       throw new ModuleLoadException(pae);
     }
   } else {
     ModuleLoader loader = Module.getCallerModuleLoader();
     ModuleIdentifier identifier = ModuleIdentifier.fromString(moduleSpec);
     return loader.loadModule(identifier).getClassLoader();
   }
 }
Esempio n. 26
0
 protected Object getInstance(
     Module module, String moduleName, String className, List<ParamValueMetaData> params)
     throws DeploymentUnitProcessingException {
   try {
     ClassLoader moduleClassLoader = null;
     if (moduleName == null) {
       moduleClassLoader = module.getClassLoader();
     } else {
       moduleClassLoader = module.getModule(ModuleIdentifier.create(moduleName)).getClassLoader();
     }
     Object instance = moduleClassLoader.loadClass(className).newInstance();
     if (params != null) {
       for (ParamValueMetaData param : params) {
         IntrospectionUtils.setProperty(instance, param.getParamName(), param.getParamValue());
       }
     }
     return instance;
   } catch (Throwable t) {
     throw new DeploymentUnitProcessingException(
         MESSAGES.failToCreateContainerComponentInstance(className), t);
   }
 }
  private static void loadRegisteredHandlers() {

    try {
      final Module module =
          Module.getBootModuleLoader()
              .loadModule(ModuleIdentifier.create("org.jboss.as.undertow", "main"));
      if (module != null) {
        for (final Handler handler : module.loadService(Handler.class)) {
          handlers.add(handler);
          handlerMap.put(handler.getName(), handler);
        }
      }
    } catch (ModuleLoadException e) {
      // e.printStackTrace();
    }
    if (handlers.isEmpty()) {
      ServiceLoader<Handler> loader = ServiceLoader.load(Handler.class);
      for (final Handler handler : loader) {
        handlers.add(handler);
        handlerMap.put(handler.getName(), handler);
      }
    }
  }
Esempio n. 28
0
  @Override
  public ClassLoader getClassLoader(ClassLoader fallbackLoader, String... classpathEntries) {
    List<ClassLoader> delegatingLoaders = new ArrayList<ClassLoader>();
    if (classpathEntries != null) {
      // each classpath entry is interpreted as a module identifier
      for (String moduleIdString : classpathEntries) {
        if (!StringUtil.isBlank(moduleIdString)) {
          try {
            ModuleIdentifier moduleIdentifier = ModuleIdentifier.fromString(moduleIdString);
            delegatingLoaders.add(moduleLoader().loadModule(moduleIdentifier).getClassLoader());
          } catch (IllegalArgumentException e) {
            LOG.warnv(
                "The string (classpath entry) is not a valid module identifier: {0}",
                moduleIdString);
          } catch (ModuleLoadException e) {
            LOG.warnv(
                "Cannot load module from (from classpath entry) with identifier: {0}",
                moduleIdString);
          }
        }
      }
    }
    ClassLoader currentLoader = getClass().getClassLoader();
    if (fallbackLoader != null && !fallbackLoader.equals(currentLoader)) {
      // if the parent of fallback is the same as the current loader, just use that
      if (fallbackLoader.getParent().equals(currentLoader)) {
        currentLoader = fallbackLoader;
      } else {
        delegatingLoaders.add(fallbackLoader);
      }
    }

    return delegatingLoaders.isEmpty()
        ? currentLoader
        : new DelegatingClassLoader(currentLoader, delegatingLoaders);
  }
  private ModuleIdentifier createAdditionalModule(
      final ResourceRoot resourceRoot,
      final DeploymentUnit topLevelDeployment,
      final VirtualFile topLevelRoot,
      final Map<VirtualFile, AdditionalModuleSpecification> additionalModules,
      final VirtualFile classPathFile,
      final ArrayDeque<RootEntry> resourceRoots)
      throws DeploymentUnitProcessingException {
    final ResourceRoot root = createResourceRoot(classPathFile);

    final String pathName = root.getRoot().getPathNameRelativeTo(topLevelRoot);
    ModuleIdentifier identifier =
        ModuleIdentifier.create(
            ServiceModuleLoader.MODULE_PREFIX + topLevelDeployment.getName() + "." + pathName);
    AdditionalModuleSpecification module = new AdditionalModuleSpecification(identifier, root);
    topLevelDeployment.addToAttachmentList(Attachments.ADDITIONAL_MODULES, module);
    additionalModules.put(classPathFile, module);
    resourceRoot.addToAttachmentList(Attachments.CLASS_PATH_RESOURCE_ROOTS, root);

    // add this to the list of roots to be processed, so transitive class path entries will be
    // respected
    resourceRoots.add(new RootEntry(module, root));
    return identifier;
  }
  private static StandaloneServer create(
      ModuleLoader moduleLoader, File jbossHomeDir, String bundlePath, String[] cmdargs) {

    setupBundlePath(bundlePath);
    setupVfsModule(moduleLoader);
    setupLoggingSystem(moduleLoader);

    // Embedded Server wants this, too. Seems redundant, but supply it.
    WildFlySecurityManager.setPropertyPrivileged(
        SYSPROP_KEY_JBOSS_HOME_DIR, jbossHomeDir.getAbsolutePath());

    // Load the Embedded Server Module
    final Module embeddedModule;
    try {
      embeddedModule = moduleLoader.loadModule(ModuleIdentifier.create(MODULE_ID_EMBEDDED));
    } catch (final ModuleLoadException mle) {
      throw EmbeddedLogger.ROOT_LOGGER.moduleLoaderError(mle, MODULE_ID_EMBEDDED, moduleLoader);
    }

    // Load the Embedded Server Factory via the modular environment
    final ModuleClassLoader embeddedModuleCL = embeddedModule.getClassLoader();
    final Class<?> embeddedServerFactoryClass;
    final Class<?> standaloneServerClass;
    try {
      embeddedServerFactoryClass =
          embeddedModuleCL.loadClass(EmbeddedStandAloneServerFactory.class.getName());
      standaloneServerClass = embeddedModuleCL.loadClass(StandaloneServer.class.getName());
    } catch (final ClassNotFoundException cnfe) {
      throw EmbeddedLogger.ROOT_LOGGER.cannotLoadEmbeddedServerFactory(
          cnfe, EmbeddedStandAloneServerFactory.class.getName());
    }

    // Get a handle to the method which will create the server
    final Method createServerMethod;
    try {
      createServerMethod =
          embeddedServerFactoryClass.getMethod(
              "create",
              File.class,
              ModuleLoader.class,
              Properties.class,
              Map.class,
              String[].class);
    } catch (final NoSuchMethodException nsme) {
      throw EmbeddedLogger.ROOT_LOGGER.cannotGetReflectiveMethod(
          nsme, "create", embeddedServerFactoryClass.getName());
    }

    // Create the server
    Object standaloneServerImpl;
    try {
      Properties sysprops = WildFlySecurityManager.getSystemPropertiesPrivileged();
      Map<String, String> sysenv = WildFlySecurityManager.getSystemEnvironmentPrivileged();
      String[] args = cmdargs != null ? cmdargs : new String[0];
      standaloneServerImpl =
          createServerMethod.invoke(null, jbossHomeDir, moduleLoader, sysprops, sysenv, args);
    } catch (final InvocationTargetException ite) {
      throw EmbeddedLogger.ROOT_LOGGER.cannotCreateStandaloneServer(
          ite.getCause(), createServerMethod);
    } catch (final IllegalAccessException iae) {
      throw EmbeddedLogger.ROOT_LOGGER.cannotCreateStandaloneServer(iae, createServerMethod);
    }
    return new StandaloneServerIndirection(standaloneServerClass, standaloneServerImpl);
  }