@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) {} }
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); } }
@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); }
@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) {} }
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); }
@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); }
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)); } }
/** * 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 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"); }
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); }
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; }
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); } } }
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; }
public static StandaloneServer create( final File jbossHomeDir, final Properties systemProps, final Map<String, String> systemEnv, String... systemPackages) throws Throwable { if (jbossHomeDir == null || jbossHomeDir.isDirectory() == false) throw new IllegalStateException("Invalid jboss.home.dir: " + jbossHomeDir); if (systemProps.getProperty(ServerEnvironment.HOME_DIR) == null) systemProps.setProperty(ServerEnvironment.HOME_DIR, jbossHomeDir.getAbsolutePath()); setupCleanDirectories(jbossHomeDir, systemProps); File modulesDir = new File(jbossHomeDir + "/modules"); final ModuleLoader moduleLoader = InitialModuleLoaderFactory.getModuleLoader(modulesDir, systemPackages); // Initialize the Logging system ModuleIdentifier logModuleId = ModuleIdentifier.create("org.jboss.logmanager"); ModuleClassLoader logModuleClassLoader = moduleLoader.loadModule(logModuleId).getClassLoader(); ClassLoader ctxClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(logModuleClassLoader); systemProps.setProperty("java.util.logging.manager", "org.jboss.logmanager.LogManager"); if (LogManager.getLogManager().getClass() == LogManager.class) { System.err.println("WARNING: Failed to load the specified logmodule " + logModuleId); } else { Module.setModuleLogger(new JDKModuleLogger()); } } finally { Thread.currentThread().setContextClassLoader(ctxClassLoader); } // Load the server Module and get its ClassLoader final ModuleIdentifier serverModuleId = ModuleIdentifier.create("org.jboss.as.server"); final Module serverModule = moduleLoader.loadModule(serverModuleId); final ModuleClassLoader serverModuleClassLoader = serverModule.getClassLoader(); StandaloneServer standaloneServer = new StandaloneServer() { private Object serviceContainer; @Override public void start() throws ServerStartException { try { // Determine the ServerEnvironment Class<?> serverMainClass = serverModuleClassLoader.loadClass(Main.class.getName()); Method determineEnvironmentMethod = serverMainClass.getMethod( "determineEnvironment", String[].class, Properties.class, Map.class); Object serverEnvironment = determineEnvironmentMethod.invoke(null, new String[0], systemProps, systemEnv); Class<?> bootstrapFactoryClass = serverModuleClassLoader.loadClass(Bootstrap.Factory.class.getName()); Method newInstanceMethod = bootstrapFactoryClass.getMethod("newInstance"); Object bootstrap = newInstanceMethod.invoke(null); Class<?> configurationClass = serverModuleClassLoader.loadClass(Bootstrap.Configuration.class.getName()); Constructor<?> configurationCtor = configurationClass.getConstructor(); Object configuration = configurationCtor.newInstance(); Method setServerEnvironmentMethod = configurationClass.getMethod( "setServerEnvironment", serverEnvironment.getClass()); setServerEnvironmentMethod.invoke(configuration, serverEnvironment); Method setModuleLoaderMethod = configurationClass.getMethod("setModuleLoader", ModuleLoader.class); setModuleLoaderMethod.invoke(configuration, moduleLoader); Class<?> bootstrapClass = serverModuleClassLoader.loadClass(Bootstrap.class.getName()); Method bootstrapStartMethod = bootstrapClass.getMethod("start", configurationClass, List.class); Object future = bootstrapStartMethod.invoke( bootstrap, configuration, Collections.<ServiceActivator>emptyList()); Class<?> asyncFutureClass = serverModuleClassLoader.loadClass(AsyncFuture.class.getName()); Method getMethod = asyncFutureClass.getMethod("get"); serviceContainer = getMethod.invoke(future); } catch (RuntimeException rte) { throw rte; } catch (Exception ex) { throw new ServerStartException(ex); } } @Override public void stop() { if (serviceContainer != null) { try { Class<?> serverContainerClass = serverModuleClassLoader.loadClass(ServiceContainer.class.getName()); Method shutdownMethod = serverContainerClass.getMethod("shutdown"); shutdownMethod.invoke(serviceContainer); Method awaitTerminationMethod = serverContainerClass.getMethod("awaitTermination"); awaitTerminationMethod.invoke(serviceContainer); } catch (RuntimeException rte) { throw rte; } catch (Exception ex) { ex.printStackTrace(); } } } }; return standaloneServer; }
private ModuleIdentifier getModuleIdentifier(final String deploymentArchive) { return ModuleIdentifier.create("deployment." + deploymentArchive); }
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); }
/** {@inheritDoc} */ public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final List<ResourceRoot> resourceRoots = DeploymentUtils.allResourceRoots(deploymentUnit); if (!DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)) { return; } final DeploymentUnit parent = deploymentUnit.getParent(); final DeploymentUnit topLevelDeployment = parent == null ? deploymentUnit : parent; final VirtualFile toplevelRoot = topLevelDeployment.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot(); final ExternalModuleService externalModuleService = topLevelDeployment.getAttachment(Attachments.EXTERNAL_MODULE_SERVICE); final Map<VirtualFile, ResourceRoot> files = new HashMap<VirtualFile, ResourceRoot>(); for (ResourceRoot resourceRoot : resourceRoots) { files.put(resourceRoot.getRoot(), resourceRoot); } final Deque<ResourceRoot> libResourceRoots = new ArrayDeque<ResourceRoot>(); // scan /lib entries for class-path items for (ResourceRoot resourceRoot : resourceRoots) { if (ModuleRootMarker.isModuleRoot(resourceRoot) && !SubDeploymentMarker.isSubDeployment(resourceRoot)) { libResourceRoots.add(resourceRoot); } } while (!libResourceRoots.isEmpty()) { final ResourceRoot resourceRoot = libResourceRoots.pop(); final String[] items = getClassPathEntries(resourceRoot); for (String item : items) { final VirtualFile classPathFile = resourceRoot.getRoot().getParent().getChild(item); if (!classPathFile.exists()) { log.warnf("Class Path entry %s in %s not found. ", item, resourceRoot.getRoot()); } else if (isInside(classPathFile, toplevelRoot)) { if (!files.containsKey(classPathFile)) { log.warnf( "Class Path entry %s in %s does not point to a valid jar for a Class-Path reference.", item, resourceRoot.getRoot()); } else { final ResourceRoot target = files.get(classPathFile); if (SubDeploymentMarker.isSubDeployment(target)) { // for now we do not allow ear Class-Path references to subdeployments log.warnf( "Class Path entry in " + resourceRoot.getRoot() + " may not point to a sub deployment."); } else if (!ModuleRootMarker.isModuleRoot(target)) { // otherwise just add it to the lib dir ModuleRootMarker.mark(target); libResourceRoots.push(target); log.debugf( "Resource %s added to logical lib directory due to Class-Path entry in %s", classPathFile, target.getRoot()); } // otherwise it is already part of lib, so we leave it alone for now } } else if (item.startsWith("/")) { ModuleIdentifier moduleIdentifier = externalModuleService.addExternalModule(item); deploymentUnit.addToAttachmentList(Attachments.CLASS_PATH_ENTRIES, moduleIdentifier); log.debugf("Resource %s added as external jar %s", classPathFile, resourceRoot.getRoot()); } else { // this is a dep on another deployment deploymentUnit.addToAttachmentList( Attachments.CLASS_PATH_ENTRIES, ModuleIdentifier.create(ServiceModuleLoader.MODULE_PREFIX + classPathFile.getName())); } } } }
/** * Responsible for adding appropriate Java EE {@link * org.jboss.as.server.deployment.module.ModuleDependency module dependencies} * * <p>Author : Jaikiran Pai */ public class EjbDependencyDeploymentUnitProcessor implements DeploymentUnitProcessor { // TODO: This should be centralized some place /** Module id for Java EE module */ private static final ModuleIdentifier JAVAEE_MODULE_IDENTIFIER = ModuleIdentifier.create("javaee.api"); /** Needed for timer handle persistence TODO: restrict visibility */ private static final ModuleIdentifier EJB_SUBSYSTEM = ModuleIdentifier.create("org.jboss.as.ejb3"); private static final ModuleIdentifier EJB_CLIENT = ModuleIdentifier.create("org.jboss.ejb-client"); private static final ModuleIdentifier EJB_IIOP_CLIENT = ModuleIdentifier.create("org.jboss.iiop-client"); private static final ModuleIdentifier JACORB = ModuleIdentifier.create("org.jboss.as.jacorb"); /** * Adds Java EE module as a dependency to any deployment unit which is a EJB deployment * * @param phaseContext the deployment unit context * @throws DeploymentUnitProcessingException */ @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { // get hold of the deployment unit DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); final ModuleLoader moduleLoader = Module.getBootModuleLoader(); final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); // we always give them the EJB client moduleSpecification.addSystemDependency( new ModuleDependency(moduleLoader, EJB_CLIENT, false, false, false)); moduleSpecification.addSystemDependency( new ModuleDependency(moduleLoader, EJB_IIOP_CLIENT, false, false, false)); // we always have to add this, as even non-ejb deployments may still lookup IIOP ejb's moduleSpecification.addSystemDependency( new ModuleDependency(moduleLoader, EJB_SUBSYSTEM, false, false, false)); if (JacORBDeploymentMarker.isJacORBDeployment(deploymentUnit)) { // needed for dynamic IIOP stubs moduleSpecification.addSystemDependency( new ModuleDependency(moduleLoader, JACORB, false, false, false)); } // fetch the EjbJarMetaData // TODO: remove the app client bit after the next EJB release if (!isEjbDeployment(deploymentUnit) && !DeploymentTypeMarker.isType(DeploymentType.APPLICATION_CLIENT, deploymentUnit)) { // nothing to do return; } // FIXME: still not the best way to do it // this must be the first dep listed in the module if (Boolean.getBoolean("org.jboss.as.ejb3.EMBEDDED")) moduleSpecification.addSystemDependency( new ModuleDependency(moduleLoader, ModuleIdentifier.CLASSPATH, false, false, false)); moduleSpecification.addSystemDependency( new ModuleDependency(moduleLoader, JAVAEE_MODULE_IDENTIFIER, false, false, false)); } @Override public void undeploy(DeploymentUnit context) {} }
public ServerEnvironment( final String hostControllerName, final Properties props, final Map<String, String> env, final String serverConfig, final ConfigurationFile.InteractionPolicy configInteractionPolicy, final LaunchType launchType, final RunningMode initialRunningMode, ProductConfig productConfig, long startTime) { assert props != null; this.launchType = launchType; this.standalone = launchType != LaunchType.DOMAIN; this.initialRunningMode = initialRunningMode == null ? RunningMode.NORMAL : initialRunningMode; this.runningModeControl = new RunningModeControl(this.initialRunningMode); this.startTime = startTime; this.hostControllerName = hostControllerName; if (standalone && hostControllerName != null) { throw ServerLogger.ROOT_LOGGER.hostControllerNameNonNullInStandalone(); } if (!standalone && hostControllerName == null) { throw ServerLogger.ROOT_LOGGER.hostControllerNameNullInDomain(); } // Calculate qualified and unqualified host names, default server name, cluster node name configureQualifiedHostName( props.getProperty(QUALIFIED_HOST_NAME), props.getProperty(HOST_NAME), props, env); // Java system-wide extension dirs javaExtDirs = getFilesFromProperty(JAVA_EXT_DIRS, props); if (launchType.equals(LaunchType.SELF_CONTAINED)) { homeDir = new File(WildFlySecurityManager.getPropertyPrivileged("user.dir", ".")); serverBaseDir = new File(WildFlySecurityManager.getPropertyPrivileged("user.dir", ".")); serverLogDir = new File(WildFlySecurityManager.getPropertyPrivileged("user.dir", ".")); try { File tmpDir = File.createTempFile("wildfly-self-contained", ".d"); if (tmpDir.exists()) { for (int i = 0; i < 10; ++i) { if (tmpDir.exists()) { if (deleteRecursively(tmpDir)) { break; } try { Thread.sleep(100); } catch (InterruptedException e) { break; } } } if (tmpDir.exists()) { throw ServerLogger.ROOT_LOGGER.unableToCreateSelfContainedDir(); } } tmpDir.mkdirs(); tmpDir.deleteOnExit(); serverTempDir = tmpDir; } catch (IOException e) { throw new RuntimeException(e); } serverDataDir = serverTempDir; modulesDir = null; serverConfigurationDir = null; serverConfigurationFile = null; controllerTempDir = null; domainBaseDir = null; domainConfigurationDir = null; WildFlySecurityManager.setPropertyPrivileged( ServerEnvironment.JBOSS_PERSIST_SERVER_CONFIG, "false"); } else { // Must have HOME_DIR homeDir = getFileFromProperty(HOME_DIR, props); if (homeDir == null) { throw ServerLogger.ROOT_LOGGER.missingHomeDirConfiguration(HOME_DIR); } if (!homeDir.exists() || !homeDir.isDirectory()) { throw ServerLogger.ROOT_LOGGER.homeDirectoryDoesNotExist(homeDir); } @SuppressWarnings("deprecation") File tmp = getFileFromProperty(MODULES_DIR, props); if (tmp == null) { tmp = new File(homeDir, "modules"); } else if (!tmp.exists() || !tmp.isDirectory()) { throw ServerLogger.ROOT_LOGGER.modulesDirectoryDoesNotExist(tmp); } modulesDir = tmp; configureBundlesDir(props.getProperty(BUNDLES_DIR), props); tmp = getFileFromProperty(SERVER_BASE_DIR, props); if (tmp == null) { tmp = new File(homeDir, standalone ? "standalone" : "domain/servers/" + serverName); } if (standalone) { if (!tmp.exists()) { throw ServerLogger.ROOT_LOGGER.serverBaseDirectoryDoesNotExist(tmp); } else if (!tmp.isDirectory()) { throw ServerLogger.ROOT_LOGGER.serverBaseDirectoryIsNotADirectory(tmp); } } else { if (tmp.exists()) { if (!tmp.isDirectory()) { throw ServerLogger.ROOT_LOGGER.serverBaseDirectoryIsNotADirectory(tmp); } } else if (!tmp.mkdirs()) { throw ServerLogger.ROOT_LOGGER.couldNotCreateServerBaseDirectory(tmp); } } serverBaseDir = tmp; tmp = getFileFromProperty(SERVER_CONFIG_DIR, props); if (tmp == null) { tmp = new File(serverBaseDir, "configuration"); } serverConfigurationDir = tmp; if (standalone && (!serverConfigurationDir.exists() || !serverConfigurationDir.isDirectory())) { throw ServerLogger.ROOT_LOGGER.configDirectoryDoesNotExist(serverConfigurationDir); } String defaultServerConfig = WildFlySecurityManager.getPropertyPrivileged( JBOSS_SERVER_DEFAULT_CONFIG, "standalone.xml"); serverConfigurationFile = standalone ? new ConfigurationFile( serverConfigurationDir, defaultServerConfig, serverConfig, configInteractionPolicy) : null; // Adds a system property to indicate whether or not the server configuration should be // persisted @SuppressWarnings("deprecation") final String propertyKey = JBOSS_PERSIST_SERVER_CONFIG; WildFlySecurityManager.setPropertyPrivileged( propertyKey, Boolean.toString( configInteractionPolicy == null || !configInteractionPolicy.isReadOnly())); tmp = getFileFromProperty(SERVER_DATA_DIR, props); if (tmp == null) { tmp = new File(serverBaseDir, "data"); } serverDataDir = tmp; if (serverDataDir.exists()) { if (!serverDataDir.isDirectory()) { throw ServerLogger.ROOT_LOGGER.serverDataDirectoryIsNotDirectory(serverDataDir); } } else { if (!serverDataDir.mkdirs()) { throw ServerLogger.ROOT_LOGGER.couldNotCreateServerDataDirectory(serverDataDir); } } tmp = getFileFromProperty(SERVER_CONTENT_DIR, props); if (tmp == null) { @SuppressWarnings("deprecation") String deprecatedProp = SERVER_DEPLOY_DIR; tmp = getFileFromProperty(deprecatedProp, props); } if (tmp == null) { tmp = new File(serverDataDir, "content"); } serverContentDir = tmp; if (serverContentDir.exists()) { if (!serverContentDir.isDirectory()) { throw ServerLogger.ROOT_LOGGER.serverContentDirectoryIsNotDirectory(serverContentDir); } } else if (!serverContentDir.mkdirs()) { throw ServerLogger.ROOT_LOGGER.couldNotCreateServerContentDirectory(serverContentDir); } tmp = getFileFromProperty(SERVER_LOG_DIR, props); if (tmp == null) { tmp = new File(serverBaseDir, "log"); } if (tmp.exists()) { if (!tmp.isDirectory()) { throw ServerLogger.ROOT_LOGGER.logDirectoryIsNotADirectory(tmp); } } else if (!tmp.mkdirs()) { throw ServerLogger.ROOT_LOGGER.couldNotCreateLogDirectory(tmp); } serverLogDir = tmp; tmp = configureServerTempDir(props.getProperty(SERVER_TEMP_DIR), props); if (tmp.exists()) { if (!tmp.isDirectory()) { throw ServerLogger.ROOT_LOGGER.serverTempDirectoryIsNotADirectory(tmp); } } else if (!tmp.mkdirs()) { throw ServerLogger.ROOT_LOGGER.couldNotCreateServerTempDirectory(tmp); } tmp = getFileFromProperty(CONTROLLER_TEMP_DIR, props); if (tmp == null) { tmp = serverTempDir; } if (tmp.exists()) { if (!tmp.isDirectory()) { throw ServerLogger.ROOT_LOGGER.controllerTempDirectoryIsNotADirectory(tmp); } } else if (!tmp.mkdirs()) { throw ServerLogger.ROOT_LOGGER.couldNotCreateControllerTempDirectory(tmp); } controllerTempDir = tmp; // Optional paths for the domain mode tmp = getFileFromProperty(DOMAIN_BASE_DIR, props); if (tmp != null) { if (!tmp.exists() || !tmp.isDirectory()) { throw ServerLogger.ROOT_LOGGER.domainBaseDirDoesNotExist(tmp); } this.domainBaseDir = tmp; } else { this.domainBaseDir = null; } tmp = getFileFromProperty(DOMAIN_CONFIG_DIR, props); if (tmp != null) { if (!tmp.exists() || !tmp.isDirectory()) { throw ServerLogger.ROOT_LOGGER.domainConfigDirDoesNotExist(tmp); } this.domainConfigurationDir = tmp; } else { this.domainConfigurationDir = null; } } boolean allowExecutor = true; String maxThreads = WildFlySecurityManager.getPropertyPrivileged(BOOTSTRAP_MAX_THREADS, null); if (maxThreads != null && maxThreads.length() > 0) { try { Integer.decode(maxThreads); // Property was set to a valid value; user wishes to control core service threads allowExecutor = false; } catch (NumberFormatException ex) { ServerLogger.ROOT_LOGGER.failedToParseCommandLineInteger(BOOTSTRAP_MAX_THREADS, maxThreads); } } allowModelControllerExecutor = allowExecutor; final Path filePath = this.serverDataDir.toPath().resolve(KERNEL_DIR).resolve(UUID_FILE); UUID uuid = null; try { uuid = obtainProcessUUID(filePath); } catch (IOException ex) { throw ServerLogger.ROOT_LOGGER.couldNotObtainServerUuidFile(ex, filePath); } this.serverUUID = uuid; this.productConfig = productConfig; // Keep a copy of the original properties this.primordialProperties = new Properties(); copyProperties(props, primordialProperties); // Create a separate copy for tracking later changes this.providedProperties = new Properties(); copyProperties(primordialProperties, providedProperties); // Provide standard system properties for environment items WildFlySecurityManager.setPropertyPrivileged(QUALIFIED_HOST_NAME, qualifiedHostName); WildFlySecurityManager.setPropertyPrivileged(HOST_NAME, hostName); WildFlySecurityManager.setPropertyPrivileged(SERVER_NAME, serverName); WildFlySecurityManager.setPropertyPrivileged(NODE_NAME, nodeName); setPathProperty(HOME_DIR, homeDir); setPathProperty(MODULES_DIR, modulesDir); setPathProperty(SERVER_BASE_DIR, serverBaseDir); setPathProperty(SERVER_CONFIG_DIR, serverConfigurationDir); setPathProperty(SERVER_DATA_DIR, serverDataDir); setPathProperty(SERVER_DEPLOY_DIR, serverContentDir); setPathProperty(SERVER_LOG_DIR, serverLogDir); setPathProperty(SERVER_TEMP_DIR, serverTempDir); if (launchType.getProcessType() == ProcessType.DOMAIN_SERVER) { if (domainBaseDir != null) { WildFlySecurityManager.setPropertyPrivileged( DOMAIN_BASE_DIR, domainBaseDir.getAbsolutePath()); } if (domainConfigurationDir != null) { WildFlySecurityManager.setPropertyPrivileged( DOMAIN_CONFIG_DIR, domainConfigurationDir.getAbsolutePath()); } } // Register the vfs module as URLStreamHandlerFactory try { ModuleLoader bootLoader = Module.getBootModuleLoader(); Module vfsModule = bootLoader.loadModule(ModuleIdentifier.create(VFS_MODULE_IDENTIFIER)); Module.registerURLStreamHandlerFactoryModule(vfsModule); } catch (Exception ex) { ServerLogger.ROOT_LOGGER.cannotAddURLStreamHandlerFactory(ex, VFS_MODULE_IDENTIFIER); } }