org.jboss.modules.ResourceLoaderSpec Java Examples

The following examples show how to use org.jboss.modules.ResourceLoaderSpec. 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: ApplicationModuleFinder.java    From thorntail with Apache License 2.0 6 votes vote down vote up
private void addClasspathJars(ModuleSpec.Builder builder) throws IOException {
    String driversList = System.getProperty("thorntail.classpath");

    if (driversList != null && driversList.trim().length() > 0) {
        String[] drivers = driversList.split(";");

        for (String driver : drivers) {
            File driverFile = new File(driver);

            if (driverFile.exists()) {
                builder.addResourceRoot(
                        ResourceLoaderSpec.createResourceLoaderSpec(
                                ResourceLoaders.createJarResourceLoader(driverFile.getName(), JarFiles.create(driverFile))
                        )
                );
            }
        }
    }
}
 
Example #2
Source File: ModuleSpecProcessor.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void addResourceRoot(final ModuleSpec.Builder specBuilder, final ResourceRoot resource, final List<PermissionFactory> permFactories)
        throws DeploymentUnitProcessingException {
    try {
        final VirtualFile root = resource.getRoot();
        if (resource.getExportFilters().isEmpty()) {
            specBuilder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(new VFSResourceLoader(resource
                    .getRootName(), root, resource.isUsePhysicalCodeSource())));
        } else {
            final MultiplePathFilterBuilder filterBuilder = PathFilters.multiplePathFilterBuilder(true);
            for (final FilterSpecification filter : resource.getExportFilters()) {
                filterBuilder.addFilter(filter.getPathFilter(), filter.isInclude());
            }
            specBuilder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(new VFSResourceLoader(resource
                    .getRootName(), root, resource.isUsePhysicalCodeSource()), filterBuilder.create()));
        }
        // start with the root
        permFactories.add(new ImmediatePermissionFactory(
                new VirtualFilePermission(root.getPathName(), VirtualFilePermission.FLAG_READ)));
        // also include all children, recursively
        permFactories.add(new ImmediatePermissionFactory(
                new VirtualFilePermission(root.getChild("-").getPathName(), VirtualFilePermission.FLAG_READ)));
    } catch (IOException e) {
        throw ServerLogger.ROOT_LOGGER.failedToCreateVFSResourceLoader(resource.getRootName(), e);
    }
}
 
Example #3
Source File: WildFlySwarmBootstrapConf.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 6 votes vote down vote up
void apply(ModuleSpec.Builder builder, MavenArtifactDescriptor entry) throws IOException {
    File artifact = MavenResolvers.get().resolveJarArtifact(entry.mscCoordinates());
    if (artifact == null) {
        throw new IOException("Unable to locate artifact: " + entry.mscGav());
    }

    if (LOG.isTraceEnabled()) {
        LOG.trace("adding bootstrap artifact: " + artifact.getAbsolutePath());
    }

    builder.addResourceRoot(
            ResourceLoaderSpec.createResourceLoaderSpec(
                    ResourceLoaders.createJarResourceLoader(artifact.getName(), new JarFile(artifact))
            )
    );
}
 
Example #4
Source File: DriverModuleBuilder.java    From thorntail with Apache License 2.0 5 votes vote down vote up
public boolean detect(final String moduleName) {

        Messages.MESSAGES.attemptToAutoDetectDriver(this.name);

        File primaryJar = attemptDetection();

        if (primaryJar != null) {
            Set<File> optionalJars = findOptionalJars();

            optionalJars.add(primaryJar);
            DynamicModuleFinder.register(moduleName, (id, loader) -> {
                ModuleSpec.Builder builder = ModuleSpec.build(id);

                for (File eachJar : optionalJars) {
                    try {
                        JarFile jar = JarFileManager.INSTANCE.addJarFile(eachJar);
                        builder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(
                                ResourceLoaders.createIterableJarResourceLoader(jar.getName(), jar)
                        ));
                    } catch (IOException e) {
                        Messages.MESSAGES.errorLoadingAutodetectedDriver(this.name, e);
                        return null;
                    }
                }

                for (String eachModuleIdentifier : driverModuleDependencies) {
                    builder.addDependency(new ModuleDependencySpecBuilder()
                            .setName(eachModuleIdentifier)
                            .build());
                }
                builder.addDependency(DependencySpec.createLocalDependencySpec());

                return builder.create();
            });
            this.installed = true;
        }
        return this.installed;
    }
 
Example #5
Source File: JBossModuleUtils.java    From Nicobar with Apache License 2.0 5 votes vote down vote up
/**
 * Populates a {@link ModuleSpec} with runtime resources, dependencies and properties from the
 * {@link ScriptCompilerPluginSpec}
 * Helpful when creating a {@link ModuleSpec} from a ScriptLibPluginSpec
 *
 * @param moduleSpecBuilder builder to populate
 * @param pluginSpec {@link ScriptCompilerPluginSpec} to copy from
 * @param latestRevisionIds used to lookup the latest dependencies. see {@link JBossModuleLoader#getLatestRevisionIds()}
 */
public static void populateCompilerModuleSpec(ModuleSpec.Builder moduleSpecBuilder, ScriptCompilerPluginSpec pluginSpec, Map<ModuleId, ModuleIdentifier> latestRevisionIds) throws ModuleLoadException {
    Objects.requireNonNull(moduleSpecBuilder, "moduleSpecBuilder");
    Objects.requireNonNull(pluginSpec, "pluginSpec");
    Objects.requireNonNull(latestRevisionIds, "latestRevisionIds");
    Set<Path> pluginRuntime = pluginSpec.getRuntimeResources();
    for (Path resourcePath : pluginRuntime) {
        File file = resourcePath.toFile();
        String pathString = resourcePath.toString();
        ResourceLoader rootResourceLoader = null;
        if (file.isDirectory()) {
            rootResourceLoader = ResourceLoaders.createFileResourceLoader(pathString, file);
        } else if (pathString.endsWith(".jar")) {
            try {
                rootResourceLoader = ResourceLoaders.createJarResourceLoader(pathString, new JarFile(file));
            } catch (IOException e) {
                throw new ModuleLoadException(e);
            }
        }
        if (rootResourceLoader != null) {
            moduleSpecBuilder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(rootResourceLoader));
        }
    }
    moduleSpecBuilder.addDependency(JRE_DEPENDENCY_SPEC);
    moduleSpecBuilder.addDependency(NICOBAR_CORE_DEPENDENCY_SPEC);
    moduleSpecBuilder.addDependency(DependencySpec.createLocalDependencySpec());
    // add dependencies to the module spec
    Set<ModuleId> dependencies = pluginSpec.getModuleDependencies();
    for (ModuleId scriptModuleId : dependencies) {
        ModuleIdentifier latestIdentifier = latestRevisionIds.get(scriptModuleId);
        if (latestIdentifier == null) {
            throw new ModuleLoadException("Cannot find dependent module: " + scriptModuleId);
        }

        moduleSpecBuilder.addDependency(DependencySpec.createModuleDependencySpec(latestIdentifier, true, false));
    }

    Map<String, String> pluginMetadata = pluginSpec.getPluginMetadata();
    addPropertiesToSpec(moduleSpecBuilder, pluginMetadata);
}
 
Example #6
Source File: JBossModuleUtils.java    From Nicobar with Apache License 2.0 5 votes vote down vote up
/**
 * Populates a builder with a {@link ResourceLoaderSpec} to a filesystem resource root.
 * {@link ScriptArchive}
 * @param moduleSpecBuilder builder to populate
 * @param compilationRoot a path to the compilation resource root directory
 */
public static void populateModuleSpecWithCompilationRoot(ModuleSpec.Builder moduleSpecBuilder, Path compilationRoot) {
    Objects.requireNonNull(moduleSpecBuilder, "moduleSpecBuilder");
    Objects.requireNonNull(compilationRoot, "resourceRoot");
    ResourceLoader resourceLoader = ResourceLoaders.createFileResourceLoader(compilationRoot.toString(), compilationRoot.toFile());
    moduleSpecBuilder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(resourceLoader));
}
 
Example #7
Source File: AddonModuleLoader.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
private void addLocalResources(AddonRepository repository, AddonId found, Builder builder, ModuleIdentifier id)
{
   List<File> resources = repository.getAddonResources(found);
   for (File file : resources)
   {
      try
      {
         if (file.isDirectory())
         {
            builder.addResourceRoot(
                     ResourceLoaderSpec.createResourceLoaderSpec(
                              ResourceLoaders.createFileResourceLoader(file.getName(), file),
                              PathFilters.acceptAll()));
         }
         else if (file.length() > 0)
         {
            JarFile jarFile = new JarFile(file);
            moduleJarFileCache.addJarFileReference(id, jarFile);
            builder.addResourceRoot(
                     ResourceLoaderSpec.createResourceLoaderSpec(
                              ResourceLoaders.createJarResourceLoader(file.getName(), jarFile),
                              PathFilters.acceptAll()));
         }
      }
      catch (IOException e)
      {
         throw new ContainerException("Could not load resources from [" + file.getAbsolutePath() + "]", e);
      }
   }
}
 
Example #8
Source File: Seam2Processor.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    if (deploymentUnit.getParent() != null) {
        return;
    }

    final List<DeploymentUnit> deploymentUnits = new ArrayList<DeploymentUnit>();
    deploymentUnits.add(deploymentUnit);
    deploymentUnits.addAll(deploymentUnit.getAttachmentList(Attachments.SUB_DEPLOYMENTS));

    for (DeploymentUnit unit : deploymentUnits) {

        final ResourceRoot mainRoot = unit.getAttachment(Attachments.DEPLOYMENT_ROOT);
        if (mainRoot == null)
            continue;

        VirtualFile root = mainRoot.getRoot();
        for (String path : SEAM_FILES) {
            if (root.getChild(path).exists()) {
                final ModuleSpecification moduleSpecification = deploymentUnit
                        .getAttachment(Attachments.MODULE_SPECIFICATION);
                final ModuleLoader moduleLoader = Module.getBootModuleLoader();
                moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, VFS_MODULE, false, false, false,
                        false)); // for VFS scanner

                try {
                    ResourceLoader resourceLoader = ResourceLoaders.createJarResourceLoader(SEAM_INT_JAR, new JarFile(
                            getSeamIntResourceRoot().getRoot().getPathName()));
                    moduleSpecification.addResourceLoader(ResourceLoaderSpec.createResourceLoaderSpec(resourceLoader));
                } catch (Exception e) {
                    throw new DeploymentUnitProcessingException(e);
                }

                unit.addToAttachmentList(Attachments.RESOURCE_ROOTS, getSeamIntResourceRoot());
                return;
            }
        }
    }
}
 
Example #9
Source File: WildFlySwarmApplicationConf.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 5 votes vote down vote up
@Override
void apply(ModuleSpec.Builder builder) throws IOException {

    int slashLoc = this.path.lastIndexOf('/');
    String name = this.path;

    if (slashLoc > 0) {
        name = this.path.substring(slashLoc + 1);
    }

    String ext = ".jar";
    int dotLoc = name.lastIndexOf('.');
    if (dotLoc > 0) {
        ext = name.substring(dotLoc);
        name = name.substring(0, dotLoc);
    }

    File tmp = TempFileManager.INSTANCE.newTempFile(name, ext);

    try (InputStream artifactIn = getClass().getClassLoader().getResourceAsStream(this.path)) {
        Files.copy(artifactIn, tmp.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }
    final String jarName = tmp.getName().toString();
    final JarFile jarFile = new JarFile(tmp);
    final ResourceLoader jarLoader = ResourceLoaders.createJarResourceLoader(jarName,
            jarFile);
    builder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(jarLoader));

    if (".war".equals(ext)) {
        final ResourceLoader warLoader = ResourceLoaders.createJarResourceLoader(jarName,
                jarFile,
                "WEB-INF/classes");
        builder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(warLoader));
    }
}
 
Example #10
Source File: WildFlySwarmApplicationConf.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 5 votes vote down vote up
@Override
void apply(ModuleSpec.Builder builder) throws IOException {
    File artifact = MavenResolvers.get().resolveJarArtifact(this.descriptor.mscCoordinates());

    if (artifact == null) {
        throw new IOException("Unable to locate artifact: " + this.descriptor.mscGav());
    }
    builder.addResourceRoot(
            ResourceLoaderSpec.createResourceLoaderSpec(
                    ResourceLoaders.createJarResourceLoader(artifact.getName(), new JarFile(artifact))
            )
    );
}
 
Example #11
Source File: ModuleSpecification.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void addResourceLoader(final ResourceLoaderSpec resourceLoader) {
    this.resourceLoaders.add(resourceLoader);
}
 
Example #12
Source File: ModuleSpecification.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public List<ResourceLoaderSpec> getResourceLoaders() {
    return Collections.unmodifiableList(resourceLoaders);
}
 
Example #13
Source File: ModuleSpecProcessor.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private ServiceName createModuleService(final DeploymentPhaseContext phaseContext, final DeploymentUnit deploymentUnit,
                                        final List<ResourceRoot> resourceRoots, final List<ResourceRoot> parentResourceRoots,
                                        final ModuleSpecification moduleSpecification, final ModuleIdentifier moduleIdentifier) throws DeploymentUnitProcessingException {
    logger.debugf("Creating module: %s", moduleIdentifier);
    final ModuleSpec.Builder specBuilder = ModuleSpec.build(moduleIdentifier);
    for (final DependencySpec dep : moduleSpecification.getModuleSystemDependencies()) {
        specBuilder.addDependency(dep);
    }
    final List<ModuleDependency> dependencies = moduleSpecification.getSystemDependencies();
    final List<ModuleDependency> localDependencies = moduleSpecification.getLocalDependencies();
    final List<ModuleDependency> userDependencies = moduleSpecification.getUserDependencies();

    final List<PermissionFactory> permFactories = moduleSpecification.getPermissionFactories();

    installAliases(moduleSpecification, moduleIdentifier, deploymentUnit, phaseContext);

    // add additional resource loaders first
    for (final ResourceLoaderSpec resourceLoaderSpec : moduleSpecification.getResourceLoaders()) {
        logger.debugf("Adding resource loader %s to module %s", resourceLoaderSpec, moduleIdentifier);
        specBuilder.addResourceRoot(resourceLoaderSpec);
    }

    for (final ResourceRoot resourceRoot : resourceRoots) {
        logger.debugf("Adding resource %s to module %s", resourceRoot.getRoot(), moduleIdentifier);
        addResourceRoot(specBuilder, resourceRoot, permFactories);
    }

    createDependencies(specBuilder, dependencies, false);
    createDependencies(specBuilder, userDependencies, false);

    if (moduleSpecification.isLocalLast()) {
        createDependencies(specBuilder, localDependencies, moduleSpecification.isLocalDependenciesTransitive());
        specBuilder.addDependency(DependencySpec.createLocalDependencySpec());
    } else {
        specBuilder.addDependency(DependencySpec.createLocalDependencySpec());
        createDependencies(specBuilder, localDependencies, moduleSpecification.isLocalDependenciesTransitive());
    }

    final Enumeration<Permission> e = DEFAULT_PERMISSIONS.elements();
    while (e.hasMoreElements()) {
        permFactories.add(new ImmediatePermissionFactory(e.nextElement()));
    }
    // TODO: servlet context temp dir FilePermission

    // add file permissions for parent roots
    for (ResourceRoot additionalParentRoot : parentResourceRoots) {
        final VirtualFile root = additionalParentRoot.getRoot();
        // start with the root
        permFactories.add(new ImmediatePermissionFactory(
                new VirtualFilePermission(root.getPathName(), VirtualFilePermission.FLAG_READ)));
        // also include all children, recursively
        permFactories.add(new ImmediatePermissionFactory(
                new VirtualFilePermission(root.getChild("-").getPathName(), VirtualFilePermission.FLAG_READ)));
    }

    FactoryPermissionCollection permissionCollection = new FactoryPermissionCollection(permFactories.toArray(new PermissionFactory[permFactories.size()]));

    specBuilder.setPermissionCollection(permissionCollection);
    deploymentUnit.putAttachment(Attachments.MODULE_PERMISSIONS, permissionCollection);

    final DelegatingClassFileTransformer delegatingClassFileTransformer = new DelegatingClassFileTransformer();
    specBuilder.setClassFileTransformer(delegatingClassFileTransformer);
    deploymentUnit.putAttachment(DelegatingClassFileTransformer.ATTACHMENT_KEY, delegatingClassFileTransformer);
    final ModuleSpec moduleSpec = specBuilder.create();
    final ServiceName moduleSpecServiceName = ServiceModuleLoader.moduleSpecServiceName(moduleIdentifier);

    ModuleDefinition moduleDefinition = new ModuleDefinition(moduleIdentifier, new HashSet<>(moduleSpecification.getAllDependencies()), moduleSpec);

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

    ModuleResolvePhaseService.installService(phaseContext.getServiceTarget(), moduleDefinition);

    return ModuleLoadService.install(phaseContext.getServiceTarget(), moduleIdentifier, dependencies, localDependencies, userDependencies);
}
 
Example #14
Source File: ExternalModuleSpecService.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static void addResourceRoot(final ModuleSpec.Builder specBuilder, final JarFile file) {
    specBuilder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(ResourceLoaders.createJarResourceLoader(file)));
}
 
Example #15
Source File: ExternalModuleSpecService.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static void addPathResourceRoot(final ModuleSpec.Builder specBuilder, Path path) {
    specBuilder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(ResourceLoaders.createPathResourceLoader(path)));
}
 
Example #16
Source File: ExtensionIndexService.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static void addResourceRoot(final ModuleSpec.Builder specBuilder, String name, JarFile jarFile) {
    specBuilder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(ResourceLoaders.createJarResourceLoader(name,
            jarFile)));
}
 
Example #17
Source File: ApplicationModuleFinder.java    From thorntail with Apache License 2.0 4 votes vote down vote up
protected void addAsset(ModuleSpec.Builder builder, ApplicationEnvironment env) throws IOException {
    String path = env.getAsset();
    if (path == null) {
        return;
    }

    int slashLoc = path.lastIndexOf('/');
    String name = path;

    if (slashLoc > 0) {
        name = path.substring(slashLoc + 1);
    }

    String ext = ".jar";
    int dotLoc = name.lastIndexOf('.');
    if (dotLoc > 0) {
        ext = name.substring(dotLoc);
        name = name.substring(0, dotLoc);
    }

    File tmp = TempFileManager.INSTANCE.newTempFile(name, ext);

    try (InputStream artifactIn = getClass().getClassLoader().getResourceAsStream(path)) {
        Files.copy(artifactIn, tmp.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }

    final String jarName = tmp.getName();
    final JarFile jarFile = JarFiles.create(tmp);

    File tmpDir = TempFileManager.INSTANCE.newTempDirectory(name, ext);

    // Explode jar due to some issues in Windows on stopping (JarFiles cannot be deleted)
    BootstrapUtil.explodeJar(jarFile, tmpDir.getAbsolutePath());

    // SWARM-1473: exploded app artifact is also used to back ShrinkWrap archive used by deployment processors
    TempFileManager.INSTANCE.setExplodedApplicationArtifact(tmpDir);

    jarFile.close();
    tmp.delete();

    final ResourceLoader jarLoader = ResourceLoaders.createFileResourceLoader(jarName, tmpDir);
    builder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(jarLoader));

    if (".war".equalsIgnoreCase(ext)) {
        final ResourceLoader warLoader = ResourceLoaders.createFileResourceLoader(jarName + "WEBINF",
                                                                                  new File(tmpDir.getAbsolutePath() + File.separator + "WEB-INF" + File.separator + "classes"));

        builder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(warLoader));
    }
}
 
Example #18
Source File: DriverInfo.java    From thorntail with Apache License 2.0 4 votes vote down vote up
public boolean detect(DatasourcesFraction fraction) {
    if (fraction.subresources().jdbcDriver(this.name) != null) {
        // already installed
        return true;
    }

    DatasourcesMessages.MESSAGES.attemptToAutoDetectJdbcDriver(this.name);

    File primaryJar = attemptDetection();

    if (primaryJar != null) {
        Set<File> optionalJars = findOptionalJars();

        optionalJars.add(primaryJar);

        fraction.jdbcDriver(this.name, (driver) -> {
            @SuppressWarnings("deprecation")
            ModuleIdentifier identifier = ModuleIdentifier.fromString(this.moduleIdentifier);
            driver.driverModuleName(identifier.getName());
            driver.moduleSlot(identifier.getSlot());
            this.configureDriver(driver);
        });

        DynamicModuleFinder.register(this.moduleIdentifier, (id, loader) -> {
            ModuleSpec.Builder builder = ModuleSpec.build(id);

            for (File eachJar : optionalJars) {
                try {
                    JarFile jar = JarFileManager.INSTANCE.addJarFile(eachJar);
                    builder.addResourceRoot(ResourceLoaderSpec.createResourceLoaderSpec(
                            ResourceLoaders.createIterableJarResourceLoader(jar.getName(), jar)
                    ));
                } catch (IOException e) {
                    DatasourcesMessages.MESSAGES.errorLoadingAutodetectedJdbcDriver(this.name, e);
                    return null;
                }
            }

            builder.addDependency(new ModuleDependencySpecBuilder()
                    .setName("javax.api")
                    .build());
            builder.addDependency(new ModuleDependencySpecBuilder()
                    .setName("javax.transactions.api")
                    .setExport(false)
                    .setOptional(true)
                    .build());
            builder.addDependency(DependencySpec.createLocalDependencySpec());
            addModuleDependencies(builder);

            return builder.create();
        });

        this.installed = true;
    }

    return this.installed;
}