org.jboss.modules.ModuleClassLoader Java Examples

The following examples show how to use org.jboss.modules.ModuleClassLoader. 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: CommandLine.java    From thorntail with Apache License 2.0 6 votes vote down vote up
public void displayConfigHelp(PrintStream out, String fraction) throws IOException, ModuleLoadException {
    ModuleClassLoader cl = Module.getBootModuleLoader().loadModule("thorntail.application").getClassLoader();
    Enumeration<URL> docs = cl.getResources("META-INF/configuration-meta.properties");

    Properties props = new Properties();

    while (docs.hasMoreElements()) {
        URL each = docs.nextElement();
        Properties fractionDocs = new Properties();
        fractionDocs.load(each.openStream());
        if (fraction.equals(ALL) || fraction.equals(fractionDocs.getProperty(FRACTION))) {
            fractionDocs.remove(FRACTION);
            props.putAll(fractionDocs);
        }
    }

    props.stringPropertyNames().stream()
            .sorted()
            .forEach(key -> {
                out.println("# " + key);
                out.println();
                out.println(formatDocs("    ", props.getProperty(key)));
                out.println();
            });
}
 
Example #2
Source File: MscRuntimeContainerDelegate.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected void deployServletProcessApplication(ServletProcessApplication processApplication) {

  ClassLoader contextClassloader = ClassLoaderUtil.getContextClassloader();
  String moduleName = ((ModuleClassLoader)contextClassloader).getModule().getIdentifier().toString();

  ServiceName serviceName = ServiceNames.forNoViewProcessApplicationStartService(moduleName);
  ServiceName paModuleService = ServiceNames.forProcessApplicationModuleService(moduleName);

  if(serviceContainer.getService(serviceName) == null) {

    ServiceController<ServiceTarget> requiredService = (ServiceController<ServiceTarget>) serviceContainer.getRequiredService(paModuleService);

    NoViewProcessApplicationStartService service = new NoViewProcessApplicationStartService(processApplication.getReference());
    requiredService.getValue()
      .addService(serviceName, service)
      .setInitialMode(Mode.ACTIVE)
      .install();

  }
}
 
Example #3
Source File: MscRuntimeContainerDelegate.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected void deployServletProcessApplication(ServletProcessApplication processApplication) {

  ClassLoader contextClassloader = ClassLoaderUtil.getContextClassloader();
  String moduleName = ((ModuleClassLoader)contextClassloader).getModule().getIdentifier().toString();

  ServiceName serviceName = ServiceNames.forNoViewProcessApplicationStartService(moduleName);
  ServiceName paModuleService = ServiceNames.forProcessApplicationModuleService(moduleName);

  if(serviceContainer.getService(serviceName) == null) {

    ServiceController<ServiceTarget> requiredService = (ServiceController<ServiceTarget>) serviceContainer.getRequiredService(paModuleService);

    NoViewProcessApplicationStartService service = new NoViewProcessApplicationStartService(processApplication.getReference());
    requiredService.getValue()
      .addService(serviceName, service)
      .setInitialMode(Mode.ACTIVE)
      .install();

  }
}
 
Example #4
Source File: JBossModuleUtilsTest.java    From Nicobar with Apache License 2.0 6 votes vote down vote up
/**
 * Verify that the module creates the expected set of dependencies for a {@link PathScriptArchive}
 */
@Test
public void testPathResources() throws Exception {
    Path jarPath = CoreTestResourceUtil.getResourceAsPath(TEST_TEXT_PATH);
    ScriptArchive jarScriptArchive = new PathScriptArchive.Builder(jarPath)
        .setModuleSpec(new ScriptModuleSpec.Builder(ModuleId.create("testModuleId"))
            .addMetadata(METADATA_NAME, METADATA_VALUE)
            .build())
        .build();
    ModuleIdentifier revisionId = JBossModuleUtils.createRevisionId(TEST_TEXT_PATH.getModuleId(), 1);
    ModuleSpec.Builder moduleSpecBuilder = ModuleSpec.build(revisionId);
    JBossModuleLoader moduleLoader = new JBossModuleLoader();
    JBossModuleUtils.populateModuleSpecWithCoreDependencies(moduleSpecBuilder, jarScriptArchive);
    JBossModuleUtils.populateModuleSpecWithResources(moduleSpecBuilder, jarScriptArchive);
    moduleLoader.addModuleSpec(moduleSpecBuilder.create());

    Module module = moduleLoader.loadModule(revisionId);
    ModuleClassLoader moduleClassLoader = module.getClassLoader();

    // verify the metadata was transfered
    assertEquals(module.getProperty(METADATA_NAME), METADATA_VALUE);
    // verify that the archive resource match exactly the module resources
    Set<String> actualPaths = getResourcePaths(moduleClassLoader);

    assertEquals(actualPaths, TEST_TEXT_PATH.getContentPaths());
}
 
Example #5
Source File: ScriptModuleLoader.java    From Nicobar with Apache License 2.0 6 votes vote down vote up
/**
 * Compiles and links the scripts within the module by locating the correct compiler
 * and delegating the compilation. the classes will be loaded into the module's classloader
 * upon completion.
 * @param module module to be compiled
 * @param moduleCompilationRoot the directory to store compiled classes in.
 */
protected void compileModule(Module module, Path moduleCompilationRoot) throws ScriptCompilationException, IOException {
    // compile the script archive for the module, and inject the resultant classes into
    // the ModuleClassLoader
    ModuleClassLoader moduleClassLoader = module.getClassLoader();
    if (moduleClassLoader instanceof JBossModuleClassLoader) {
        JBossModuleClassLoader jBossModuleClassLoader = (JBossModuleClassLoader)moduleClassLoader;
        ScriptArchive scriptArchive = jBossModuleClassLoader.getScriptArchive();
        List<ScriptArchiveCompiler> candidateCompilers = findCompilers(scriptArchive);
        if (candidateCompilers.size() == 0) {
            throw new ScriptCompilationException("Could not find a suitable compiler for this archive.");
        }

        // Compile iteratively
        for (ScriptArchiveCompiler compiler: candidateCompilers) {
            compiler.compile(scriptArchive, jBossModuleClassLoader, moduleCompilationRoot);
        }
    }
}
 
Example #6
Source File: CamelUndertowHostService.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
private void validateEndpointContextPath(URI httpURI) {
    String undertowEndpointPath = getContextPath(httpURI);
    Set<Deployment> deployments = defaultHost.getDeployments();
    for (Deployment deployment : deployments) {
        DeploymentInfo depInfo = deployment.getDeploymentInfo();
        String contextPath = depInfo.getContextPath();
        if (contextPath.equals(undertowEndpointPath)) {
            final HttpHandler handler = deployment.getHandler();
            if (handler instanceof CamelEndpointDeployerHandler && ((CamelEndpointDeployerHandler)handler).getRoutingHandler() instanceof DelegatingRoutingHandler) {
                final ModuleClassLoader oldCl = ((DelegatingRoutingHandler)((CamelEndpointDeployerHandler)handler).getRoutingHandler()).classLoader;
                final ModuleClassLoader tccl = checkTccl();
                if (tccl != oldCl) {
                    // Avoid allowing handlers from distinct apps to handle the same path
                    throw new IllegalStateException("Cannot add "+ HttpHandler.class.getName() +" for path " + contextPath + " defined in " + tccl.getName() + " because that path is already served by "+ oldCl.getName());
                }
            } else {
                // Another application already serves this path
                throw new IllegalStateException("Cannot overwrite context path " + contextPath + " owned by " + depInfo.getDeploymentName());
            }
        }
    }
}
 
Example #7
Source File: RuntimeVaultReader.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * This constructor should remain protected to keep the vault as invisible
 * as possible, but it needs to be exposed for service plug-ability.
 */
public RuntimeVaultReader() {
    //if PB is not available we want to throw an exception here
    //also if we are in a modular environment we want to avoid loading/linking
    //the picketbox module, as loading the module too early breaks
    //EE8 preview mode
    if(getClass().getClassLoader() instanceof ModuleClassLoader) {
        if (!Module.getBootModuleLoader().iterateModules("org.picketbox", false).hasNext()) {
            throw new RuntimeException();
        }
    } else {
        try {
            Class.forName("org.jboss.security.vault.SecurityVaultFactory");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example #8
Source File: Main.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static void runBootableJar(Path jbossHome, List<String> arguments, Long unzipTime) throws Exception {
    final String modulePath = jbossHome.resolve(JBOSS_MODULES_DIR_NAME).toAbsolutePath().toString();
    ModuleLoader moduleLoader = setupModuleLoader(modulePath);
    final Module bootableJarModule;
    try {
        bootableJarModule = moduleLoader.loadModule(MODULE_ID_JAR_RUNTIME);
    } catch (final ModuleLoadException mle) {
        throw new Exception(mle);
    }

    final ModuleClassLoader moduleCL = bootableJarModule.getClassLoader();
    final Class<?> bjFactoryClass;
    try {
        bjFactoryClass = moduleCL.loadClass(BOOTABLE_JAR);
    } catch (final ClassNotFoundException cnfe) {
        throw new Exception(cnfe);
    }
    Method runMethod;
    try {
        runMethod = bjFactoryClass.getMethod(BOOTABLE_JAR_RUN_METHOD, Path.class, List.class, ModuleLoader.class, ModuleClassLoader.class, Long.class);
    } catch (final NoSuchMethodException nsme) {
        throw new Exception(nsme);
    }
    runMethod.invoke(null, jbossHome, arguments, moduleLoader, moduleCL, unzipTime);
}
 
Example #9
Source File: BootableJar.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Modular entry point.
 *
 * @param jbossHome Server home directory.
 * @param args User provided arguments.
 * @param moduleLoader JBoss modules loader.
 * @param moduleClassLoader Bootable jar module classloader
 * @param unzipTime Time spent to unzip the server.
 * @throws Exception
 */
public static void run(Path jbossHome, List<String> args, ModuleLoader moduleLoader, ModuleClassLoader moduleClassLoader, Long unzipTime) throws Exception {
    setTccl(moduleClassLoader);
    Arguments arguments;
    try {
        arguments = Arguments.parseArguments(args);
    } catch (Throwable ex) {
        System.err.println(ex);
        CmdUsage.printUsage(System.out);
        return;
    }
    if (arguments.isHelp()) {
        CmdUsage.printUsage(System.out);
        return;
    }
    BootableJar bootableJar = new BootableJar(jbossHome, arguments, moduleLoader, unzipTime);
    bootableJar.run();
}
 
Example #10
Source File: EmbeddedProcessFactory.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static Object createManagedProcess(final ProcessType embeddedType, final Method createServerMethod, final Configuration configuration, ModuleClassLoader embeddedModuleCL) {
    Object serverImpl;
    try {
        Properties sysprops = getSystemPropertiesPrivileged();
        Map<String, String> sysenv = getSystemEnvironmentPrivileged();
        String[] args = configuration.getCommandArguments();
        if (embeddedModuleCL == null) {
            serverImpl = createServerMethod.invoke(null, configuration.getJBossHome().toFile(), configuration.getModuleLoader(), sysprops, sysenv, args);
        } else {
            serverImpl = createServerMethod.invoke(null, configuration.getJBossHome().toFile(), configuration.getModuleLoader(), sysprops, sysenv, args, embeddedModuleCL);
        }
    } catch (final InvocationTargetException ite) {
        if (embeddedType == ProcessType.HOST_CONTROLLER) {
            throw EmbeddedLogger.ROOT_LOGGER.cannotCreateHostController(ite.getCause(), createServerMethod);
        }
        throw EmbeddedLogger.ROOT_LOGGER.cannotCreateStandaloneServer(ite.getCause(), createServerMethod);
    } catch (final IllegalAccessException iae) {
        if (embeddedType == ProcessType.HOST_CONTROLLER) {
            throw EmbeddedLogger.ROOT_LOGGER.cannotCreateHostController(iae, createServerMethod);
        }
        throw EmbeddedLogger.ROOT_LOGGER.cannotCreateStandaloneServer(iae, createServerMethod);
    }
    return serverImpl;
}
 
Example #11
Source File: CommandLine.java    From thorntail with Apache License 2.0 6 votes vote down vote up
public void dumpYaml(PrintStream out, String fraction) throws IOException, ModuleLoadException {
    ModuleClassLoader cl = Module.getBootModuleLoader().loadModule("thorntail.application").getClassLoader();
    Enumeration<URL> docs = cl.getResources("META-INF/configuration-meta.properties");

    Properties props = new Properties();

    while (docs.hasMoreElements()) {
        URL each = docs.nextElement();
        Properties fractionDocs = new Properties();
        fractionDocs.load(each.openStream());
        if (fraction.equals(ALL) || fraction.equals(fractionDocs.getProperty(FRACTION))) {
            fractionDocs.remove(FRACTION);
            props.putAll(fractionDocs);
        }
    }

    YamlDumper.dump(out, props);
}
 
Example #12
Source File: LoggerContext.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void restore() {
    final Module logModule;
    try {
        logModule = moduleLoader.loadModule(MODULE_ID_LOGGING);
    } catch (final ModuleLoadException mle) {
        throw EmbeddedLogger.ROOT_LOGGER.moduleLoaderError(mle, MODULE_ID_LOGGING, moduleLoader);
    }

    final ModuleClassLoader logModuleClassLoader = logModule.getClassLoader();
    final ClassLoader tccl = getTccl();
    try {
        setTccl(logModuleClassLoader);
        final ModuleLogger loggerToRestore = this.loggerToRestore;
        if (loggerToRestore == null) {
            Module.setModuleLogger(NoopModuleLogger.getInstance());
        } else {
            Module.setModuleLogger(loggerToRestore);
        }
    } finally {
        // Reset TCCL
        setTccl(tccl);
    }
}
 
Example #13
Source File: LoggerContext.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void activate() {
    final Module logModule;
    try {
        logModule = moduleLoader.loadModule(MODULE_ID_LOGGING);
    } catch (final ModuleLoadException mle) {
        throw EmbeddedLogger.ROOT_LOGGER.moduleLoaderError(mle, MODULE_ID_LOGGING, moduleLoader);
    }

    final ModuleClassLoader logModuleClassLoader = logModule.getClassLoader();
    final ClassLoader tccl = getTccl();
    try {
        setTccl(logModuleClassLoader);
        loggerToRestore = Module.getModuleLogger();
        Module.setModuleLogger(new JBossLoggingModuleLogger());
    } finally {
        // Reset TCCL
        setTccl(tccl);
    }
}
 
Example #14
Source File: JBossModuleClassLoader.java    From Nicobar with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a ModuleClassLoaderFactory that produces a {@link JBossModuleClassLoader}.
 * This method is necessary to inject our custom {@link ModuleClassLoader} into
 * the {@link ModuleSpec}
 */
protected static ModuleClassLoaderFactory createFactory(final ScriptArchive scriptArchive) {
    return new ModuleClassLoaderFactory() {
        public ModuleClassLoader create(final Configuration configuration) {
            return AccessController.doPrivileged(
                new PrivilegedAction<JBossModuleClassLoader>() {
                    public JBossModuleClassLoader run() {
                        return new JBossModuleClassLoader(configuration, scriptArchive);
                    }
                });
        }
    };
}
 
Example #15
Source File: SpringJeeNamespaceTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadHandlersFromSpringContext() throws Exception {
    ModuleLoader moduleLoader = Module.getCallerModuleLoader();
    ModuleClassLoader classLoader = moduleLoader.loadModule("org.springframework.context").getClassLoader();
    URL resurl = classLoader.getResource("META-INF/spring.handlers");
    Assert.assertNotNull("URL not null", resurl);
}
 
Example #16
Source File: SpringJeeNamespaceTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadHandlersFromCamel() throws Exception {
    ModuleLoader moduleLoader = Module.getCallerModuleLoader();
    ModuleClassLoader classLoader = moduleLoader.loadModule("org.apache.camel").getClassLoader();
    URL resurl = classLoader.getResource("META-INF/spring.handlers");
    Assert.assertNotNull("URL not null", resurl);
}
 
Example #17
Source File: CXFResourcesTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testAccessFromCXFModule() throws Exception {
    ModuleLoader moduleLoader = Module.getCallerModuleLoader();
    ModuleIdentifier modid = ModuleIdentifier.create("org.apache.cxf");
    ModuleClassLoader classLoader = moduleLoader.loadModule(modid).getClassLoader();
    URL resurl = classLoader.getResource("META-INF/cxf/cxf.xml");
    Assert.assertNotNull("URL not null", resurl);
}
 
Example #18
Source File: CXFResourcesTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testAccessFromCXFComponentModule() throws Exception {
    ModuleLoader moduleLoader = Module.getCallerModuleLoader();
    ModuleIdentifier modid = ModuleIdentifier.create("org.apache.camel.component.cxf");
    ModuleClassLoader classLoader = moduleLoader.loadModule(modid).getClassLoader();
    URL resurl = classLoader.getResource("META-INF/cxf/cxf.xml");
    Assert.assertNotNull("URL not null", resurl);
}
 
Example #19
Source File: CXFResourcesTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #20
Source File: TestUtils.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
public static String getClassLoaderModuleName(ClassLoader classLoader) {
    if (classLoader instanceof ModuleClassLoader) {
        ModuleClassLoader moduleClassLoader = (ModuleClassLoader) classLoader;
        return moduleClassLoader.getModule().getName();
    }

    throw new IllegalArgumentException("ClassLoader must be of type ModuleClassLoader");
}
 
Example #21
Source File: ConfigSupport.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
public static void applyConfigChange(Path jbossHome, List<String> configs, boolean enable) throws Exception {

        IllegalStateAssertion.assertFalse(configs.isEmpty(), "No configurations specified");

        Iterator<ConfigPlugin> itsrv;
        ClassLoader classLoader = ConfigSupport.class.getClassLoader();

        // In wildfly every plugin lives in its own module.
        // The module identity corresponds to the config name
        if (classLoader instanceof ModuleClassLoader) {
            List<ConfigPlugin> plugins = new ArrayList<>();
            for (String config : configs) {
                ModuleLoader moduleLoader = Module.getCallerModuleLoader();
                ModuleIdentifier modid = ModuleIdentifier.create("org.wildfly.extras.config.plugin." + config);
                ModuleClassLoader modcl = moduleLoader.loadModule(modid).getClassLoader();
                Iterator<ConfigPlugin> auxit = ServiceLoader.load(ConfigPlugin.class, modcl).iterator();
                while (auxit.hasNext()) {
                    plugins.add(auxit.next());
                }
            }
            itsrv = plugins.iterator();
        } else {
            itsrv = ServiceLoader.load(ConfigPlugin.class, classLoader).iterator();
        }

        while (itsrv.hasNext()) {
            ConfigPlugin plugin = itsrv.next();
            if (configs.contains(plugin.getConfigName())) {

                ConfigLogger.info("Processing config for: " + plugin.getConfigName());

                applyLayerChanges(jbossHome, plugin, enable);
                applyConfigurationChanges(jbossHome, plugin, enable);
            }
        }
    }
 
Example #22
Source File: ModuleProviderLoaderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public ProviderLoader create(KeycloakDeploymentInfo info, ClassLoader baseClassLoader, String resource) {
    try {
        Module module = Module.getContextModuleLoader().loadModule(ModuleIdentifier.fromString(resource));
        ModuleClassLoader classLoader = module.getClassLoader();
        return new DefaultProviderLoader(info, classLoader);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #23
Source File: ModuleThemeProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void init(Config.Scope config) {
    String[] modules = config.getArray("modules");
    if (modules != null) {
        try {
            for (String moduleSpec : modules) {
                Module module = Module.getContextModuleLoader().loadModule(ModuleIdentifier.fromString(moduleSpec));
                ModuleClassLoader classLoader = module.getClassLoader();
                loadThemes(classLoader, classLoader.getResourceAsStream(KEYCLOAK_THEMES_JSON));
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to load themes", e);
        }
    }
}
 
Example #24
Source File: ServerReloadHelper.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void executeOperation(Object deploymentOperations, String operation) throws Exception {
    Class defaultBootModuleLoaderHolder = this.getClass().getClassLoader().loadClass("org.jboss.modules.DefaultBootModuleLoaderHolder");
    Field instance = defaultBootModuleLoaderHolder.getDeclaredField("INSTANCE");
    instance.setAccessible(true);
    ModuleLoader loader = (ModuleLoader) instance.get(null);
    Module module = loader.loadModule(ModuleIdentifier.fromString("org.jboss.as.deployment-scanner"));
    traceln("ServerLoaderhelper", "Module " + module.toString() + " loaded.");
    ModuleClassLoader cl = module.getClassLoader();
    Class modelNodeClass = cl.loadClassLocal("org.jboss.dmr.ModelNode");
    traceln("ServerLoaderhelper", "org.jboss.dmr.ModelNode class loaded.");
    Object modelNode = modelNodeClass.newInstance();
    Method getMethod = modelNodeClass.getDeclaredMethod("get", String.class);
    Method setMethod = modelNodeClass.getDeclaredMethod("set", String.class);
    Method setAddressMethod = modelNodeClass.getDeclaredMethod("set", modelNodeClass);
    Method setEmptyListMethod = modelNodeClass.getDeclaredMethod("setEmptyList");
    Object operationNode = getMethod.invoke(modelNode, "operation");
    setMethod.invoke(operationNode, operation);
    Object operationAddressNode = getMethod.invoke(modelNode, "address");
    Object addressNode = modelNodeClass.newInstance();
    setEmptyListMethod.invoke(addressNode);
    setAddressMethod.invoke(operationAddressNode, addressNode);
    traceln("ServerLoaderhelper", "We have computed the following operation " + modelNode.toString());
    for (Method deployMethod : deploymentOperations.getClass().getDeclaredMethods()) {
        if ("deploy".equals(deployMethod.getName())) {
            deployMethod.setAccessible(true);
            traceln("ServerLoaderhelper", "We have found the execution method.");
            deployMethod.invoke(deploymentOperations, modelNode, null);
            traceln("ServerLoaderhelper", "We have executed the following operation: " + modelNode.toString());
        }
    }
}
 
Example #25
Source File: ScriptModuleLoader.java    From Nicobar with Apache License 2.0 5 votes vote down vote up
/**
 * Add a language plugin to this module
 * @param pluginSpec
 * @throws ModuleLoadException
 */
public synchronized void addCompilerPlugin(ScriptCompilerPluginSpec pluginSpec) throws ModuleLoadException  {
    Objects.requireNonNull(pluginSpec, "pluginSpec");
    ModuleIdentifier pluginModuleId = JBossModuleUtils.getPluginModuleId(pluginSpec);
    ModuleSpec.Builder moduleSpecBuilder = ModuleSpec.build(pluginModuleId);
    Map<ModuleId, ModuleIdentifier> latestRevisionIds = jbossModuleLoader.getLatestRevisionIds();
    JBossModuleUtils.populateCompilerModuleSpec(moduleSpecBuilder, pluginSpec, latestRevisionIds);
    // Add app package dependencies, while blocking them from leaking (being exported) to downstream modules
    // TODO: We expose the full set of app packages to the compiler too.
    // Maybe more control over what is exposed is needed here.
    JBossModuleUtils.populateModuleSpecWithAppImports(moduleSpecBuilder, appClassLoader, appPackagePaths);
    ModuleSpec moduleSpec = moduleSpecBuilder.create();

    // spin up the module, and get the compiled classes from it's classloader
    String providerClassName = pluginSpec.getPluginClassName();
    if (providerClassName != null) {
        jbossModuleLoader.addModuleSpec(moduleSpec);
        Module pluginModule = jbossModuleLoader.loadModule(pluginModuleId);
        ModuleClassLoader pluginClassLoader = pluginModule.getClassLoader();
        Class<?> compilerProviderClass;
        try {
            compilerProviderClass = pluginClassLoader.loadClass(providerClassName);
            ScriptCompilerPlugin pluginBootstrap = (ScriptCompilerPlugin) compilerProviderClass.newInstance();
            Set<? extends ScriptArchiveCompiler> pluginCompilers = pluginBootstrap.getCompilers(pluginSpec.getCompilerParams());
            compilers.addAll(pluginCompilers);
        } catch (Exception e) {
            throw new ModuleLoadException(e);
        }

        // Save classloader away, in case clients would like access to compiler plugin's classes.
        compilerClassLoaders.put(pluginSpec.getPluginId(), pluginModule.getClassLoader());
    }
}
 
Example #26
Source File: SpringExcludedPathsTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testAccessFromCamelSpringModule() throws Exception {
    ModuleLoader moduleLoader = Module.getCallerModuleLoader();
    ModuleIdentifier modid = ModuleIdentifier.create("org.apache.camel.spring");
    ModuleClassLoader classLoader = moduleLoader.loadModule(modid).getClassLoader();
    Class<?> loadedClass = classLoader.loadClass("org.apache.camel.spring.SpringCamelContext");
    Assert.assertNotNull("Class not null", loadedClass);
    loadedClass = classLoader.loadClass("org.apache.camel.spring.remoting.CamelServiceExporter");
    Assert.assertNotNull("Class not null", loadedClass);
}
 
Example #27
Source File: JBossModuleUtilsTest.java    From Nicobar with Apache License 2.0 5 votes vote down vote up
/**
 * Verify that the module creates the expected set of dependencies for a {@link ScriptCompilerPlugin}
 */
@Test
public void testExpectedPluginDependencies() throws Exception {
    ScriptCompilerPluginSpec pluginSpec = new ScriptCompilerPluginSpec.Builder("TestPlugin")
        .addMetatdata(METADATA_NAME, METADATA_VALUE)
        .build();
    ModuleIdentifier pluginId = JBossModuleUtils.getPluginModuleId(pluginSpec);
    ModuleSpec.Builder moduleSpecBuilder = ModuleSpec.build(pluginId);
    JBossModuleUtils.populateCompilerModuleSpec(moduleSpecBuilder, pluginSpec, Collections.<ModuleId, ModuleIdentifier>emptyMap());

    JBossModuleLoader moduleLoader = new JBossModuleLoader();
    moduleLoader.addModuleSpec(moduleSpecBuilder.create());
    Module module = moduleLoader.loadModule(pluginId);
    assertNotNull(module);
    ModuleClassLoader moduleClassLoader = module.getClassLoader();

    // verify the metadata was transfered
    assertEquals(module.getProperty(METADATA_NAME), METADATA_VALUE);

    // verify the module can import the core classes
    assertNotNull(moduleClassLoader.loadClass(ScriptCompilerPlugin.class.getName()));

    // verify the module can find the JDK classes
    assertNotNull(moduleClassLoader.loadClass("org.w3c.dom.Element"));

    // verify that nothing else from the classpath leaked through
    assertClassNotFound(TestNG.class.getName(), moduleClassLoader);
}
 
Example #28
Source File: JBossModuleUtilsTest.java    From Nicobar with Apache License 2.0 5 votes vote down vote up
/**
 * Verify that the module creates the expected set of dependencies for a {@link JarScriptArchive}
 */
@Test
public void testJarResources() throws Exception {
    Path jarPath = CoreTestResourceUtil.getResourceAsPath(TEST_TEXT_JAR);
    ScriptArchive jarScriptArchive = new JarScriptArchive.Builder(jarPath)
            .setModuleSpec(new ScriptModuleSpec.Builder(ModuleId.create("testModuleId"))
            .addMetadata(METADATA_NAME, METADATA_VALUE)
            .build())
        .build();

    ModuleIdentifier revisionId = JBossModuleUtils.createRevisionId(TEST_TEXT_JAR.getModuleId(), 1);
    ModuleSpec.Builder moduleSpecBuilder = ModuleSpec.build(revisionId);
    JBossModuleLoader moduleLoader = new JBossModuleLoader();
    JBossModuleUtils.populateModuleSpecWithCoreDependencies(moduleSpecBuilder, jarScriptArchive);
    JBossModuleUtils.populateModuleSpecWithResources(moduleSpecBuilder, jarScriptArchive);

    moduleLoader.addModuleSpec(moduleSpecBuilder.create());
    Module module = moduleLoader.loadModule(revisionId);
    ModuleClassLoader moduleClassLoader = module.getClassLoader();

    // verify the metadata was transfered
    assertEquals(module.getProperty(METADATA_NAME), METADATA_VALUE);
    // verify that the archive resource match exactly the module resources
    Set<String> actualPaths = getResourcePaths(moduleClassLoader);

    assertEquals(actualPaths, TEST_TEXT_JAR.getContentPaths());
}
 
Example #29
Source File: AuthenticationContextAssociationProcessor.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void deploy(DeploymentPhaseContext context) throws DeploymentUnitProcessingException {
    AuthenticationContext authenticationContext = context.getAttachment(AUTHENTICATION_CONTEXT_KEY);
    ModuleClassLoader classLoader = context.getDeploymentUnit().getAttachment(MODULE).getClassLoader();
    if (authenticationContext != null) {
        AuthenticationContext.getContextManager().setClassLoaderDefault(
                classLoader, authenticationContext);
    } else {
        AuthenticationContext.getContextManager().setClassLoaderDefaultSupplier(
                classLoader, new Supplier<AuthenticationContext>() {

                    private volatile AuthenticationContext context;

                    @Override
                    public AuthenticationContext get() {
                        if (context != null) {
                            return context;
                        }
                        synchronized (this) {
                            if (context != null) {
                                return context;
                            }
                            return context = doPrivileged((PrivilegedAction<AuthenticationContext>) () -> {
                                ClassLoader old = Thread.currentThread().getContextClassLoader();
                                try {
                                    Thread.currentThread().setContextClassLoader(classLoader);
                                    return ElytronXmlParser.parseAuthenticationClientConfiguration().create();
                                } catch (Throwable t) {
                                    throw new InvalidAuthenticationConfigurationException(t);
                                } finally {
                                    Thread.currentThread().setContextClassLoader(old);
                                }
                            });
                        }
                    }
                });

    }
}
 
Example #30
Source File: JBossModuleUtilsTest.java    From Nicobar with Apache License 2.0 5 votes vote down vote up
private void assertClassNotFound(String className, ModuleClassLoader moduleClassLoader) {
    Class<?> foundClass;
    try {
        foundClass = moduleClassLoader.loadClass(className);
    } catch (ClassNotFoundException e) {
        foundClass = null;
    }
    assertNull(foundClass);
}