Example usage for org.springframework.boot.loader.archive Archive getUrl

List of usage examples for org.springframework.boot.loader.archive Archive getUrl

Introduction

In this page you can find the example usage for org.springframework.boot.loader.archive Archive getUrl.

Prototype

URL getUrl() throws MalformedURLException;

Source Link

Document

Returns a URL that can be used to load the archive.

Usage

From source file:com.hurence.logisland.classloading.PluginLoader.java

/**
 * Scan for plugins./*from w w  w  .j  a v  a2s.co  m*/
 */
private static void scanAndRegisterPlugins() {
    Set<URL> urls = new HashSet<>();
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    while (cl != null) {
        if (cl instanceof URLClassLoader) {
            urls.addAll(Arrays.asList(((URLClassLoader) cl).getURLs()));
            cl = cl.getParent();
        }
    }

    for (URL url : urls) {
        try {
            Archive archive = null;
            try {
                archive = new JarFileArchive(
                        new File(URLDecoder.decode(url.getFile(), Charset.defaultCharset().name())), url);
            } catch (Exception e) {
                //silently swallowing exception. just skip the archive since not an archive
            }
            if (archive == null) {
                continue;
            }
            Manifest manifest = archive.getManifest();
            if (manifest != null) {
                String exportedPlugins = manifest.getMainAttributes()
                        .getValue(ManifestAttributes.MODULE_EXPORTS);
                if (exportedPlugins != null) {
                    String version = StringUtils.defaultIfEmpty(
                            manifest.getMainAttributes().getValue(ManifestAttributes.MODULE_VERSION),
                            "UNKNOWN");

                    logger.info("Loading components from module {}", archive.getUrl().toExternalForm());

                    final Archive arc = archive;

                    if (StringUtils.isNotBlank(exportedPlugins)) {
                        Arrays.stream(exportedPlugins.split(",")).map(String::trim).forEach(s -> {
                            if (registry.putIfAbsent(s, PluginClassloaderBuilder.build(arc)) == null) {
                                logger.info("Registered component '{}' version '{}'", s, version);
                            }

                        });
                    }
                }
            }

        } catch (Exception e) {
            logger.error("Unable to load components from " + url.toExternalForm(), e);
        }
    }
}

From source file:org.springframework.cloud.dataflow.app.launcher.ModuleLauncher.java

public void launchAggregatedModules(List<ModuleLaunchRequest> moduleLaunchRequests,
        Map<String, String> aggregateArgs) {
    try {/*w  w  w .  ja  v  a 2 s  .  c o m*/
        List<String> mainClassNames = new ArrayList<>();
        LinkedHashSet<URL> jarURLs = new LinkedHashSet<>();
        List<String> seenArchives = new ArrayList<>();
        final List<String[]> arguments = new ArrayList<>();
        final ClassLoader classLoader;
        if (!(aggregateArgs.containsKey(EXCLUDE_DEPENDENCIES_ARG)
                || aggregateArgs.containsKey(INCLUDE_DEPENDENCIES_ARG))) {
            for (ModuleLaunchRequest moduleLaunchRequest : moduleLaunchRequests) {
                Resource resource = resolveModule(moduleLaunchRequest.getModule());
                JarFileArchive jarFileArchive = new JarFileArchive(resource.getFile());
                jarURLs.add(jarFileArchive.getUrl());
                for (Archive archive : jarFileArchive.getNestedArchives(ArchiveMatchingEntryFilter.FILTER)) {
                    // avoid duplication based on unique JAR names
                    String urlAsString = archive.getUrl().toString();
                    String jarNameWithExtension = urlAsString.substring(0, urlAsString.lastIndexOf("!/"));
                    String jarNameWithoutExtension = jarNameWithExtension
                            .substring(jarNameWithExtension.lastIndexOf("/") + 1);
                    if (!seenArchives.contains(jarNameWithoutExtension)) {
                        seenArchives.add(jarNameWithoutExtension);
                        jarURLs.add(archive.getUrl());
                    }
                }
                mainClassNames.add(jarFileArchive.getMainClass());
                arguments.add(toArgArray(moduleLaunchRequest.getArguments()));
            }
            classLoader = ClassloaderUtils.createModuleClassloader(jarURLs.toArray(new URL[jarURLs.size()]));
        } else {
            // First, resolve modules and extract main classes - while slightly less efficient than just
            // doing the same processing after resolution, this ensures that module artifacts are processed
            // correctly for extracting their main class names. It is not possible in the general case to
            // identify, after resolution, whether a resource represents a module artifact which was part of the
            // original request or not. We will include the first module as root and the next as direct dependencies
            Coordinates root = null;
            ArrayList<Coordinates> includeCoordinates = new ArrayList<>();
            for (ModuleLaunchRequest moduleLaunchRequest : moduleLaunchRequests) {
                Coordinates moduleCoordinates = toCoordinates(moduleLaunchRequest.getModule());
                if (root == null) {
                    root = moduleCoordinates;
                } else {
                    includeCoordinates.add(toCoordinates(moduleLaunchRequest.getModule()));
                }
                Resource moduleResource = resolveModule(moduleLaunchRequest.getModule());
                JarFileArchive moduleArchive = new JarFileArchive(moduleResource.getFile());
                mainClassNames.add(moduleArchive.getMainClass());
                arguments.add(toArgArray(moduleLaunchRequest.getArguments()));
            }
            for (String include : StringUtils
                    .commaDelimitedListToStringArray(aggregateArgs.get(INCLUDE_DEPENDENCIES_ARG))) {
                includeCoordinates.add(toCoordinates(include));
            }
            // Resolve all artifacts - since modules have been specified as direct dependencies, they will take
            // precedence in the resolution order, ensuring that the already resolved artifacts will be returned as
            // part of the response.
            Resource[] libraries = moduleResolver.resolve(root,
                    includeCoordinates.toArray(new Coordinates[includeCoordinates.size()]),
                    StringUtils.commaDelimitedListToStringArray(aggregateArgs.get(EXCLUDE_DEPENDENCIES_ARG)));
            for (Resource library : libraries) {
                jarURLs.add(library.getURL());
            }
            classLoader = new URLClassLoader(jarURLs.toArray(new URL[jarURLs.size()]));
        }

        final List<Class<?>> mainClasses = new ArrayList<>();
        for (String mainClass : mainClassNames) {
            mainClasses.add(ClassUtils.forName(mainClass, classLoader));
        }
        Runnable moduleAggregatorRunner = new ModuleAggregatorRunner(classLoader, mainClasses,
                toArgArray(aggregateArgs), arguments);
        Thread moduleAggregatorRunnerThread = new Thread(moduleAggregatorRunner);
        moduleAggregatorRunnerThread.setContextClassLoader(classLoader);
        moduleAggregatorRunnerThread.setName(MODULE_AGGREGATOR_RUNNER_THREAD_NAME);
        moduleAggregatorRunnerThread.start();
    } catch (Exception e) {
        throw new RuntimeException("failed to start aggregated modules: "
                + StringUtils.collectionToCommaDelimitedString(moduleLaunchRequests), e);
    }
}

From source file:org.springframework.cloud.dataflow.app.launcher.MultiArchiveLauncher.java

@Override
protected void launch(String[] args, String mainClass, ClassLoader classLoader) throws Exception {
    if (log.isDebugEnabled()) {
        for (Archive archive : archives) {
            log.debug("Launching with: " + archive.getUrl().toString());
        }//from w  w w. j  a  v  a 2 s . co m
    }
    if (ClassUtils.isPresent("org.apache.catalina.webresources.TomcatURLStreamHandlerFactory", classLoader)) {
        // Ensure the method is invoked on a class that is loaded by the provided
        // class loader (not the current context class loader):
        Method method = ReflectionUtils.findMethod(
                classLoader.loadClass("org.apache.catalina.webresources.TomcatURLStreamHandlerFactory"),
                "disable");
        ReflectionUtils.invokeMethod(method, null);
    }
    super.launch(args, mainClass, classLoader);
}

From source file:org.springframework.cloud.deployer.thin.ThinJarAppWrapper.java

protected String getMainClass(Archive archive) {
    try {/*from ww w.  j a v  a2 s.  c  o m*/
        Manifest manifest = archive.getManifest();
        String mainClass = null;
        if (manifest != null) {
            mainClass = manifest.getMainAttributes().getValue("Start-Class");
        }
        if (mainClass == null) {
            throw new IllegalStateException("No 'Start-Class' manifest entry specified in " + this);
        }
        return mainClass;
    } catch (Exception e) {
        try {
            File root = new File(archive.getUrl().toURI());
            if (archive instanceof ExplodedArchive) {
                return MainClassFinder.findSingleMainClass(root);
            } else {
                return MainClassFinder.findSingleMainClass(new JarFile(root), "/");
            }
        } catch (Exception ex) {
            throw new IllegalStateException("Cannot find main class", e);
        }
    }
}

From source file:org.springframework.cloud.deployer.thin.ThinJarAppWrapper.java

private URL[] getUrls(List<Archive> archives, Archive... roots) {
    try {//w ww .  j  a v a  2  s. c om
        List<URL> urls = new ArrayList<URL>(archives.size());
        for (Archive archive : archives) {
            urls.add(archive.getUrl());
        }
        for (int i = 0; i < roots.length; i++) {
            urls.add(i, roots[i].getUrl());
        }
        URL[] result = urls.toArray(new URL[0]);
        for (int i = 0; i < roots.length; i++) {
            result = ArchiveUtils.addNestedClasses(roots[i], result, "BOOT-INF/classes/");
        }
        return result;
    } catch (MalformedURLException e) {
        throw new IllegalStateException("Cannot create URL", e);
    }
}