Java Code Examples for org.jboss.modules.Module#getClassLoader()

The following examples show how to use org.jboss.modules.Module#getClassLoader() . 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: ContextCreateHandlerRegistryIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testHandlerRegistry() throws Exception {
    ContextCreateHandlerRegistry handlerRegistry = ServiceLocator.getRequiredService(CamelConstants.CONTEXT_CREATE_HANDLER_REGISTRY_SERVICE_NAME, ContextCreateHandlerRegistry.class);
    ModuleLoader moduleLoader = Module.getCallerModuleLoader();

    deployer.deploy(CAMEL_TEST_JAR);

    Module module = moduleLoader.loadModule(ModuleIdentifier.create("deployment.camel-test.jar"));
    ClassLoader classLoader = module.getClassLoader();

    // Registry should have classloader key after deploy
    Assert.assertTrue(handlerRegistry.containsKey(classLoader));

    deployer.undeploy(CAMEL_TEST_JAR);

    // Registry should have removed classloader key after undeploy
    Assert.assertFalse("Expected registry to not contain key: " + classLoader, handlerRegistry.containsKey(classLoader));
}
 
Example 2
Source File: ModuleUsageProvider.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Override
public String getRawUsageText() throws Exception {
    Module module = Module.getBootModuleLoader().loadModule("thorntail.application");
    ClassLoader cl = module.getClassLoader();

    InputStream in = cl.getResourceAsStream(META_INF_USAGE_TXT);

    if (in == null) {
        in = cl.getResourceAsStream(WEB_INF_USAGE_TXT);
    }

    if (in == null) {
        in = cl.getResourceAsStream(USAGE_TXT);
    }

    if (in != null) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
            return reader
                    .lines()
                    .collect(Collectors.joining("\n"));
        }
    }

    return null;
}
 
Example 3
Source File: CamelContextBootstrapProcessor.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Override
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {

    final DeploymentUnit depUnit = phaseContext.getDeploymentUnit();

    final Module module = depUnit.getAttachment(Attachments.MODULE);
    final String runtimeName = depUnit.getName();

    // Add the camel context bootstraps to the deployment
    CamelDeploymentSettings depSettings = depUnit.getAttachment(CamelDeploymentSettings.ATTACHMENT_KEY);
    for (URL contextURL : depSettings.getCamelContextUrls()) {
        ClassLoader tccl = SecurityActions.getContextClassLoader();
        try {
            SecurityActions.setContextClassLoader(module.getClassLoader());
            SpringCamelContextBootstrap bootstrap = new SpringCamelContextBootstrap(contextURL, module.getClassLoader());
            depUnit.addToAttachmentList(CamelConstants.CAMEL_CONTEXT_BOOTSTRAP_KEY, bootstrap);
        } catch (Exception ex) {
            throw new IllegalStateException("Cannot create camel context: " + runtimeName, ex);
        } finally {
            SecurityActions.setContextClassLoader(tccl);
        }
    }
}
 
Example 4
Source File: FaviconHandler.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 6 votes vote down vote up
public Response toResponse(NotFoundException e) {
    if (e.getMessage().contains("favicon.ico")) {
        try {
            Module module = Module.getBootModuleLoader().loadModule(ModuleIdentifier.create("org.wildfly.swarm.undertow", "runtime"));
            ClassLoader cl = module.getClassLoader();
            final InputStream in = cl.getResourceAsStream("favicon.ico");
            if (in != null) {
                Response.ResponseBuilder builder = Response.ok();
                builder.entity(in);
                return builder.build();
            }
        } catch (ModuleLoadException e1) {
            throw e;
        }
    }

    // can't handle it, rethrow.
    throw e;
}
 
Example 5
Source File: KeycloakProviderDeploymentProcessor.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    KeycloakAdapterConfigService config = KeycloakAdapterConfigService.INSTANCE;
    String deploymentName = deploymentUnit.getName();

    if (config.isKeycloakServerDeployment(deploymentName)) {
        return;
    }

    KeycloakDeploymentInfo info = KeycloakProviderDependencyProcessor.getKeycloakProviderDeploymentInfo(deploymentUnit);
    
    ScriptProviderDeploymentProcessor.deploy(deploymentUnit, info);
    
    if (info.isProvider()) {
        logger.infov("Deploying Keycloak provider: {0}", deploymentUnit.getName());
        final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
        ProviderManager pm = new ProviderManager(info, module.getClassLoader());
        ProviderManagerRegistry.SINGLETON.deploy(pm);
        deploymentUnit.putAttachment(ATTACHMENT_KEY, pm);
    }
}
 
Example 6
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 7
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 8
Source File: ClassLoadingAttributeDefinitions.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
static ClassLoader resolveClassLoader(String module) throws ModuleLoadException {
    Module current = Module.getCallerModule();
    if (module != null && current != null) {
        ModuleIdentifier mi = ModuleIdentifier.fromString(module);
        current = current.getModule(mi);
    }

    return current != null ? current.getClassLoader() : ClassLoadingAttributeDefinitions.class.getClassLoader();
}
 
Example 9
Source File: SecurityActions.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static <T> T internalLoadAndInstantiateFromModule(String moduleId, final Class<T> iface, final String name) throws Exception {
    ModuleLoader loader = Module.getCallerModuleLoader();
    final Module module = loader.loadModule(ModuleIdentifier.fromString(moduleId));
    ClassLoader cl = WildFlySecurityManager.isChecking() ? doPrivileged(new GetModuleClassLoaderAction(module)) : module.getClassLoader();
    Class<?> clazz = cl.loadClass(name);
    return iface.cast(clazz.newInstance());
}
 
Example 10
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 11
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 12
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 13
Source File: ProcessApplicationDeploymentProcessor.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected Map<String, byte[]> getDeploymentResources(ProcessArchiveXml processArchive, DeploymentUnit deploymentUnit, VirtualFile processesXmlFile) {

    final Module module = deploymentUnit.getAttachment(MODULE);

    Map<String, byte[]> resources = new HashMap<String, byte[]>();

    // first, add all resources listed in the processe.xml
    List<String> process = processArchive.getProcessResourceNames();
    ModuleClassLoader classLoader = module.getClassLoader();

    for (String resource : process) {
      InputStream inputStream = null;
      try {
        inputStream = classLoader.getResourceAsStream(resource);
        resources.put(resource, IoUtil.readInputStream(inputStream, resource));
      } finally {
        IoUtil.closeSilently(inputStream);
      }
    }

    // scan for process definitions
    if(PropertyHelper.getBooleanProperty(processArchive.getProperties(), ProcessArchiveXml.PROP_IS_SCAN_FOR_PROCESS_DEFINITIONS, process.isEmpty())) {

      //always use VFS scanner on JBoss
      final VfsProcessApplicationScanner scanner = new VfsProcessApplicationScanner();

      String resourceRootPath = processArchive.getProperties().get(ProcessArchiveXml.PROP_RESOURCE_ROOT_PATH);
      String[] additionalResourceSuffixes = StringUtil.split(processArchive.getProperties().get(ProcessArchiveXml.PROP_ADDITIONAL_RESOURCE_SUFFIXES), ProcessArchiveXml.PROP_ADDITIONAL_RESOURCE_SUFFIXES_SEPARATOR);
      URL processesXmlUrl = vfsFileAsUrl(processesXmlFile);
      resources.putAll(scanner.findResources(classLoader, resourceRootPath, processesXmlUrl, additionalResourceSuffixes));
    }

    return resources;
  }
 
Example 14
Source File: ApplicationEnvironment.java    From thorntail with Apache License 2.0 5 votes vote down vote up
public ClassLoader getBootstrapClassLoader() throws ModuleLoadException {
    if (this.mode == Mode.UBERJAR) {
        try {
            //ClassLoader cl = Module.getBootModuleLoader().loadModule("org.wildfly.swarm.bootstrap").getClassLoader();
            Module module = Module.getBootModuleLoader().loadModule("org.wildfly.swarm.bootstrap");
            ClassLoader cl = module.getClassLoader();
            return cl;
        } catch (ModuleLoadException e) {
            // ignore
        }
    }
    return ApplicationEnvironment.class.getClassLoader();
}
 
Example 15
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 16
Source File: FaviconErrorHandler.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    boolean faviconHandled = false;

    if (!exchange.isResponseComplete() && exchange.getRequestPath().contains("favicon.ico")) {

        try (InputStream faviconStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("favicon.ico")) {
            if (faviconStream != null) {
                // Load from WAR
                faviconHandled = writeFavicon(faviconStream, exchange);
            }
        }

        if (!faviconHandled) {
            Module module = Module.getBootModuleLoader().loadModule("org.wildfly.swarm.undertow:runtime");
            ClassLoader cl = module.getClassLoader();

            try (InputStream in = cl.getResourceAsStream("favicon-default.ico")) {
                if (in != null) {
                    // Return default
                    faviconHandled = writeFavicon(in, exchange);
                }
            }
        }
    }

    if (!faviconHandled) {
        this.next.handleRequest(exchange);
    }
}
 
Example 17
Source File: WildFlyClassResolver.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
WildFlyClassResolver(Module module) {
    IllegalArgumentAssertion.assertNotNull(module, "module");
    this.classLoader = module.getClassLoader();
    this.moduleId = module.getIdentifier();
}
 
Example 18
Source File: CustomModuleTest.java    From thorntail with Apache License 2.0 4 votes vote down vote up
@Test
public void testModuleDirectoryResources() throws ModuleLoadException, IOException {
    Module module = Module.getBootModuleLoader().loadModule("com.mycorp.mymodule");

    assertNotNull(module);

    ClassLoader cl = module.getClassLoader();
    assertNotNull(cl);

    URL resourceUrl = cl.getResource("subdir/stuff.txt");

    assertNotNull(resourceUrl);

    String content = null;

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(resourceUrl.openStream()))) {
        content = String.join("\n", reader.lines().collect(Collectors.toList()));
    }

    assertEquals(content, "this is dir stuff.txt");
}
 
Example 19
Source File: ClassLoaderConfigLocator.java    From thorntail with Apache License 2.0 4 votes vote down vote up
public static ClassLoaderConfigLocator forApplication() throws ModuleLoadException {
    Module appModule = Module.getBootModuleLoader().loadModule(Swarm.APPLICATION_MODULE_NAME);
    return new ClassLoaderConfigLocator(appModule.getClassLoader());
}
 
Example 20
Source File: CustomModuleTest.java    From thorntail with Apache License 2.0 4 votes vote down vote up
@Test
public void testRootJarResources() throws ModuleLoadException, IOException {
    Module module = Module.getBootModuleLoader().loadModule("com.mycorp.mymodule");

    assertNotNull(module);

    ClassLoader cl = module.getClassLoader();
    assertNotNull(cl);

    URL resourceUrl = cl.getResource("root.txt");

    assertNotNull(resourceUrl);

    String content = null;

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(resourceUrl.openStream()))) {
        content = String.join("\n", reader.lines().collect(Collectors.toList()));
    }

    assertEquals(content, "this is root.txt");
}