Example usage for org.springframework.core.io Resource getURL

List of usage examples for org.springframework.core.io Resource getURL

Introduction

In this page you can find the example usage for org.springframework.core.io Resource getURL.

Prototype

URL getURL() throws IOException;

Source Link

Document

Return a URL handle for this resource.

Usage

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

public void launchAggregatedModules(List<ModuleLaunchRequest> moduleLaunchRequests,
        Map<String, String> aggregateArgs) {
    try {/*from  ww  w.j a v a2  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.context.expression.ApplicationContextExpressionTests.java

@Test
public void resourceInjection() throws IOException {
    System.setProperty("logfile", "do_not_delete_me.txt");
    try (AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(
            ResourceInjectionBean.class)) {
        ResourceInjectionBean resourceInjectionBean = ac.getBean(ResourceInjectionBean.class);
        Resource resource = new ClassPathResource("do_not_delete_me.txt");
        assertEquals(resource, resourceInjectionBean.resource);
        assertEquals(resource.getURL(), resourceInjectionBean.url);
        assertEquals(resource.getURI(), resourceInjectionBean.uri);
        assertEquals(resource.getFile(), resourceInjectionBean.file);
        assertArrayEquals(FileCopyUtils.copyToByteArray(resource.getInputStream()),
                FileCopyUtils.copyToByteArray(resourceInjectionBean.inputStream));
        assertEquals(FileCopyUtils.copyToString(new EncodedResource(resource).getReader()),
                FileCopyUtils.copyToString(resourceInjectionBean.reader));
    } finally {// w w w  .  j  av  a2s  . com
        System.getProperties().remove("logfile");
    }
}

From source file:org.springframework.core.io.support.PathMatchingResourcePatternResolver.java

/**
 * Find all resources that match the given location pattern via the
 * Ant-style PathMatcher. Supports resources in jar files and zip files
 * and in the file system./*from w w w .ja v  a2  s  .co  m*/
 * @param locationPattern the location pattern to match
 * @return the result as Resource array
 * @throws IOException in case of I/O errors
 * @see #doFindPathMatchingJarResources
 * @see #doFindPathMatchingFileResources
 * @see org.springframework.util.PathMatcher
 */
protected Resource[] findPathMatchingResources(String locationPattern) throws IOException {
    String rootDirPath = determineRootDir(locationPattern);
    String subPattern = locationPattern.substring(rootDirPath.length());
    Resource[] rootDirResources = getResources(rootDirPath);
    Set<Resource> result = new LinkedHashSet<>(16);
    for (Resource rootDirResource : rootDirResources) {
        rootDirResource = resolveRootDirResource(rootDirResource);
        URL rootDirUrl = rootDirResource.getURL();
        if (equinoxResolveMethod != null) {
            if (rootDirUrl.getProtocol().startsWith("bundle")) {
                URL resolvedUrl = (URL) ReflectionUtils.invokeMethod(equinoxResolveMethod, null, rootDirUrl);
                if (resolvedUrl != null) {
                    rootDirUrl = resolvedUrl;
                }
                rootDirResource = new UrlResource(rootDirUrl);
            }
        }
        if (rootDirUrl.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
            result.addAll(VfsResourceMatchingDelegate.findMatchingResources(rootDirUrl, subPattern,
                    getPathMatcher()));
        } else if (ResourceUtils.isJarURL(rootDirUrl) || isJarResource(rootDirResource)) {
            result.addAll(doFindPathMatchingJarResources(rootDirResource, rootDirUrl, subPattern));
        } else {
            result.addAll(doFindPathMatchingFileResources(rootDirResource, subPattern));
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Resolved location pattern [" + locationPattern + "] to resources " + result);
    }
    return result.toArray(new Resource[result.size()]);
}

From source file:org.springframework.data.hadoop.configuration.ConfigurationFactoryBean.java

public void afterPropertiesSet() throws Exception {
    internalConfig = createConfiguration(configuration);

    internalConfig.setClassLoader(beanClassLoader);
    if (resources != null) {
        for (Resource resource : resources) {
            internalConfig.addResource(resource.getURL());
        }//  ww  w  . jav a 2  s  .  com
    }

    ConfigurationUtils.addProperties(internalConfig, properties);

    // set hdfs / fs URI last to override all other properties
    if (StringUtils.hasText(fsUri)) {
        internalConfig.set("fs.default.name", fsUri.trim());
    }

    if (StringUtils.hasText(jtUri)) {
        internalConfig.set("mapred.job.tracker", jtUri.trim());
    }

    if (initialize) {
        internalConfig.size();
    }

    postProcessConfiguration(internalConfig);

    if (registerJvmUrl) {
        try {
            // force UGI init to prevent infinite loop - see SHDP-92
            UserGroupInformation.setConfiguration(internalConfig);
            URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory(getObject()));
            log.info("Registered HDFS URL stream handler");
        } catch (Error err) {
            log.warn("Cannot register Hadoop URL stream handler - one is already registered");
        }
    }
}

From source file:org.springframework.data.hadoop.mapreduce.ExecutionUtils.java

static ClassLoader createParentLastClassLoader(Resource jar, ClassLoader parentClassLoader, Configuration cfg) {
    ClassLoader cl = null;//  w  ww  .j  a  v  a 2 s. c  o  m

    // sanity check
    if (parentClassLoader == null) {
        parentClassLoader = ClassUtils.getDefaultClassLoader();
        cl = parentClassLoader;
    }

    // check if a custom CL is needed
    if (jar != null) {
        // check if unjarring is required (it's a legacy JAR)
        try {
            if (isLegacyJar(jar)) {
                URL[] extractedURLs = expandedJarClassPath(jar, cfg);
                cl = new ParentLastURLClassLoader(extractedURLs, parentClassLoader);
            } else {
                cl = new ParentLastURLClassLoader(new URL[] { jar.getURL() }, parentClassLoader);
            }

        } catch (IOException e) {
            throw new IllegalStateException("Cannot open jar file", e);
        }
    }

    return cl;
}

From source file:org.springframework.extensions.config.source.UrlConfigSource.java

/**
 * Processes the given JAR file pattern source. The classpath
 * will be searched for JAR files that contain files that match
 * the given pattern./*from   w w w.j  ava 2  s .c  o  m*/
 * 
 * NOTE: Currently only files within the META-INF folder are supported
 * i.e. patterns that look like "jar:*!/META-INF/[filename]"
 * 
 * @param sourcePattern The wildcard pattern for files to find within JARs
 */
protected void processWildcardJarSource(String sourcePattern) {
    String file = sourcePattern.substring(7);

    if (file.startsWith(META_INF) == false) {
        throw new UnsupportedOperationException(
                "Only JAR file wildcard searches within the META-INF folder are currently supported");
    }

    try {
        if (applicationContext == null) {
            // get a list of all the JAR files that have the META-INF folder
            Enumeration<URL> urls = this.getClass().getClassLoader().getResources(META_INF);
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                // only add the item if is a reference to a JAR file
                if (url.getProtocol().equals(JarConfigSource.JAR_PROTOCOL)) {
                    URLConnection conn = url.openConnection();
                    if (conn instanceof JarURLConnection) {
                        // open the jar file and see if it contains what we're looking for
                        JarURLConnection jarConn = (JarURLConnection) conn;
                        JarFile jar = ((JarURLConnection) conn).getJarFile();
                        ZipEntry entry = jar.getEntry(file);
                        if (entry != null) {
                            if (logger.isInfoEnabled())
                                logger.info("Found " + file + " in " + jarConn.getJarFileURL());

                            String sourceString = JarConfigSource.JAR_PROTOCOL + ":"
                                    + jarConn.getJarFileURL().toExternalForm()
                                    + JarConfigSource.JAR_PATH_SEPARATOR + file;

                            super.addSourceString(sourceString);
                        } else if (logger.isDebugEnabled()) {
                            logger.debug("Did not find " + file + " in " + jarConn.getJarFileURL());
                        }
                    }
                }
            }
        } else {
            Resource[] resources = applicationContext.getResources(PREFIX_CLASSPATH_ALL + file);

            for (Resource resource : resources) {
                URL resourceUrl = resource.getURL();
                if (ResourceUtils.isJarURL(resourceUrl)
                        || ResourceUtils.URL_PROTOCOL_VFSZIP.equals(resourceUrl.getProtocol())) {
                    URL jarURL = extractJarFileURL(resourceUrl);

                    String sourceString = JarConfigSource.JAR_PROTOCOL + ":" + jarURL.toString()
                            + JarConfigSource.JAR_PATH_SEPARATOR + file;

                    super.addSourceString(sourceString);
                } else if (ResourceUtils.URL_PROTOCOL_VFS.equals(resourceUrl.getProtocol())) {
                    super.addSourceString(resourceUrl.toString());
                }
            }
        }
    } catch (IOException ioe) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to process JAR file wildcard: " + sourcePattern, ioe);
    }
}

From source file:org.springframework.extensions.webscripts.ClassPathStore.java

public void init() {
    // wrap the application context resource resolver with our own
    this.resolver = new ClassPathStoreResourceResolver(applicationContext);

    // check if there are any resources that live under this path
    // this is valid for read-only classpaths (class files + JAR file contents)
    try {/*www.  j ava 2  s  .  c  o m*/
        Resource[] resources = resolver.getResources("classpath*:" + classPath + "/*");
        if (resources.length != 0) {
            exists = true;
        } else {
            resources = resolver.getResources("classpath*:" + classPath + "/**/*");
            exists = (resources.length != 0);
        }

        if (exists) {
            // NOTE: Locate root of web script store
            // NOTE: Following awkward approach is used to mirror lookup of web scripts within store.  This
            //       ensures root paths match.
            try {
                List<String> storeDirList = null;
                // Process each root resource - there may be several as the classpath* could match
                // multiple location that each contain the configured path.
                Resource rootResource = null;
                resources = resolver.getResources("classpath*:" + classPath + "*");
                if (resources.length == 0) {
                    // the resolver may not be able to visit root folders using the pattern
                    // so get contents and manually walk up path to resolve a root
                    // this only appears to occur for a JBoss VFS directory outside of the war file location
                    resources = resolver.getResources("classpath*:" + classPath + "/*");
                    if (resources.length != 0) {
                        String externalForm = resources[0].getURL().toExternalForm();
                        externalForm = externalForm.substring(0, externalForm.lastIndexOf('/'));
                        if (externalForm.endsWith(classPath)) {
                            storeDirList = new ArrayList<String>(1);
                            storeDirList.add(externalForm);
                        }
                    }
                } else {
                    storeDirList = new ArrayList<String>(resources.length);
                    for (Resource resource : resources) {
                        String externalForm = resource.getURL().toExternalForm();
                        if (externalForm.endsWith(classPath) || externalForm.endsWith(classPath + "/")) {
                            // we've found the right resource, let's now bind using string constructor
                            // so that Spring 3 will correctly create relative paths
                            String directoryPath = resource.getFile().getAbsolutePath();
                            if (resource.getFile().isDirectory() && !directoryPath.endsWith("/")) {
                                directoryPath += "/";
                            }
                            if (new FileSystemResource(directoryPath).exists()) {
                                // retrieve file system directory
                                storeDirList.add(resource.getFile().toURI().toURL().toExternalForm());
                            }
                        }
                    }
                }
                if (storeDirList != null && storeDirList.size() != 0) {
                    this.storeDirs = storeDirList.toArray(new String[storeDirList.size()]);
                }
            } catch (IOException ioErr) {
                // unable to resolve a storeDir - this is expected for certain protocols such as "vfszip"
                // it is not critical and those protocols don't require it during path resolution later
                if (logger.isDebugEnabled())
                    logger.debug("Unable to resolve storeDir for base path " + classPath);
            }
        }
    } catch (IOException ioe) {
        throw new WebScriptException("Failed to initialise Web Script Store classpath: " + classPath, ioe);
    }

    if (!exists && mustExist) {
        throw new WebScriptException(
                "Web Script Store classpath:" + classPath + " must exist; it was not found");
    }
}

From source file:org.springframework.extensions.webscripts.ClassPathStore.java

public long lastModified(String documentPath) throws IOException {
    long mod = -1L;

    Resource document = this.getDocumentResource(documentPath);
    if (document != null) {
        mod = document.getURL().openConnection().getLastModified();
    }//from w  w  w . ja v a2  s.  c o  m

    return mod;
}

From source file:org.springframework.extensions.webscripts.ClassPathStore.java

public InputStream getDocument(String documentPath) throws IOException {
    Resource document = this.getDocumentResource(documentPath);

    if (document == null || !document.exists()) {
        throw new IOException("Document " + documentPath + " does not exist within store " + getBasePath());
    }// w  w  w.ja  v  a2 s  .com

    if (logger.isTraceEnabled())
        logger.trace("getDocument: documentPath: " + documentPath + " , storePath: "
                + document.getURL().toExternalForm());

    return document.getInputStream();
}

From source file:org.springframework.extensions.webscripts.ClassPathStore.java

/**
 * Gets resources that match a given location pattern.  A resource in the returned array can live
 * in the class path as either a class file or as an entry within one of the JAR files in the
 * class path.//from w w w. j  a  v  a  2  s.  co m
 * 
 * @param locationPattern String
 * 
 * @return Resource[] of resource that match location pattern - can be empty but never null
 * 
 * @throws IOException
 */
private Resource[] getDocumentResources(String locationPattern) throws IOException {
    String resourcePath = toResourcePath(locationPattern);

    Resource[] resources = resolver.getResources("classpath*:" + resourcePath);
    ArrayList<Resource> list = new ArrayList<Resource>(resources.length);
    for (Resource resource : resources) {
        // only keep documents, not directories
        if (!resource.getURL().toExternalForm().endsWith("/")) {
            list.add(resource);
        }
    }

    return list.toArray(new Resource[list.size()]);
}