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.osgi.web.deployer.internal.util.JasperUtils.java

/**
 * Creates a temporary jar using the given resources.
 * /*from w w w . j av  a 2  s . co  m*/
 * @param resource
 * @return
 */
private static URL createTaglibJar(Resource[] resources, Manifest mf) throws IOException {
    File tempJar = File.createTempFile("spring.dm.tld.", ".jar");
    tempJar.deleteOnExit();
    OutputStream fos = new FileOutputStream(tempJar);

    Map entries = new LinkedHashMap();
    for (int i = 0; i < resources.length; i++) {
        Resource resource = resources[i];
        String name = URLDecoder.decode(resource.getURL().getPath(), "UTF8");
        entries.put(name, resource);
    }
    JarUtils.createJar(mf, entries, fos);

    URL jarURL = tempJar.toURL();
    if (log.isTraceEnabled()) {
        StringBuilder buf = new StringBuilder();
        buf.append("\n");
        for (Iterator iterator = entries.entrySet().iterator(); iterator.hasNext();) {
            Map.Entry entry = (Map.Entry) iterator.next();
            buf.append(entry.getKey());
            buf.append("\t\t");
            buf.append(entry.getValue());
            buf.append("\n");
        }

        log.trace("Created TLD jar at " + tempJar.toURL() + " containing " + buf);
    }

    return jarURL;
}

From source file:org.springframework.richclient.application.splash.SimpleSplashScreen.java

/**
 * Load image from path.//from   w ww.  jav a  2 s .  c  om
 * 
 * @param path Path to image.
 * @return Image
 * @throws IOException
 * 
 * @throws NullPointerException if {@code path} is null.
 */
private Image loadImage(Resource path) throws IOException {
    URL url = path.getURL();
    if (url == null) {
        logger.warn("Unable to locate splash screen in classpath at: " + path);
        return null;
    }
    return Toolkit.getDefaultToolkit().createImage(url);
}

From source file:org.springframework.richclient.image.Handler.java

protected URLConnection openConnection(URL url) throws IOException {
    if (!StringUtils.hasText(url.getPath())) {
        throw new MalformedURLException("must provide an image key.");
    } else if (StringUtils.hasText(url.getHost())) {
        throw new MalformedURLException("host part should be empty.");
    } else if (url.getPort() != -1) {
        throw new MalformedURLException("port part should be empty.");
    } else if (StringUtils.hasText(url.getQuery())) {
        throw new MalformedURLException("query part should be empty.");
    } else if (StringUtils.hasText(url.getRef())) {
        throw new MalformedURLException("ref part should be empty.");
    } else if (StringUtils.hasText(url.getUserInfo())) {
        throw new MalformedURLException("user info part should be empty.");
    }/*from w w w.j  a  va2  s .c  o m*/
    urlHandlerImageSource.getImage(url.getPath());
    Resource image = urlHandlerImageSource.getImageResource(url.getPath());
    if (image != null)
        return image.getURL().openConnection();

    throw new IOException("null image returned for key [" + url.getFile() + "].");
}

From source file:org.springframework.scheduling.quartz.ResourceLoaderClassLoadHelper.java

@Override
@Nullable//from w  ww .  jav a  2s  .  c  o  m
public URL getResource(String name) {
    Assert.state(this.resourceLoader != null, "ResourceLoaderClassLoadHelper not initialized");
    Resource resource = this.resourceLoader.getResource(name);
    if (resource.exists()) {
        try {
            return resource.getURL();
        } catch (IOException ex) {
            if (logger.isWarnEnabled()) {
                logger.warn("Could not load " + resource);
            }
            return null;
        }
    } else {
        return getClassLoader().getResource(name);
    }
}

From source file:org.springframework.xd.dirt.plugins.spark.streaming.SparkStreamingPlugin.java

/**
 * Get the list of jars that this spark module requires.
 *
 * @return the list of spark application jars
 *///from  w w w  .ja  v  a 2 s  .  c  om
private List<String> getApplicationJars(Module module) {
    // Get jars from module classpath
    URLClassLoader classLoader = (URLClassLoader) ((SimpleModule) module).getClassLoader();
    List<String> jars = new ArrayList<String>();
    for (URL url : classLoader.getURLs()) {
        String file = url.getFile().split("\\!", 2)[0];
        if (file.endsWith(".jar")) {
            jars.add(file);
        }
    }
    // Get message bus libraries
    Environment env = this.getApplicationContext().getEnvironment();
    String jarsLocation = env.resolvePlaceholders(MessageBusClassLoaderFactory.MESSAGE_BUS_JARS_LOCATION);
    try {
        Resource[] resources = resolver.getResources(jarsLocation);
        for (Resource resource : resources) {
            URL url = resource.getURL();
            jars.add(url.getFile());
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
    // Get necessary dependencies from XD DIRT.
    URLClassLoader parentClassLoader = (URLClassLoader) classLoader.getParent();
    URL[] urls = parentClassLoader.getURLs();
    for (URL url : urls) {
        String file = FilenameUtils.getName(url.getFile());
        String fileToAdd = url.getFile().split("\\!", 2)[0];
        if (file.endsWith(".jar") && (// Add spark jars
        file.contains("spark") ||
        // Add SpringXD dependencies
                file.contains("spring-xd-") ||
                // Add Spring dependencies
                file.contains("spring-core") || file.contains("spring-integration-core")
                || file.contains("spring-beans") || file.contains("spring-context")
                || file.contains("spring-boot") || file.contains("spring-aop")
                || file.contains("spring-expression") || file.contains("spring-messaging")
                || file.contains("spring-retry") || file.contains("spring-tx")
                || file.contains("spring-data-commons") || file.contains("spring-data-redis")
                || file.contains("commons-pool") || file.contains("jedis") ||
                // Add codec dependency
                file.contains("kryo") || file.contains("gs-collections"))) {
            jars.add(fileToAdd);
        }
    }
    return jars;
}

From source file:org.springframework.xml.sax.SaxUtils.java

/** Retrieves the URL from the given resource as System ID. Returns <code>null</code> if it cannot be opened. */
public static String getSystemId(Resource resource) {
    try {//from   ww w .  j a v a  2 s .  c o  m
        return new URI(resource.getURL().toExternalForm()).toString();
    } catch (IOException ex) {
        logger.debug("Could not get System ID from [" + resource + "], ex");
        return null;
    } catch (URISyntaxException e) {
        logger.debug("Could not get System ID from [" + resource + "], ex");
        return null;
    }
}

From source file:org.springframework.yarn.configuration.ConfigurationFactoryBean.java

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

    internalConfig.setClassLoader(beanClassLoader);
    if (resources != null) {
        for (Resource resource : resources) {
            internalConfig.addResource(resource.getURL());
        }//from  w w  w.  j  av  a  2 s .c o  m
    }

    ConfigurationUtils.addProperties(internalConfig, properties);

    // set hdfs / fs URI last to override all other properties
    if (StringUtils.hasText(fsUri)) {
        log.info("Overwriting fsUri=[" + internalConfig.get(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY)
                + "] with fsUri=[" + fsUri.trim() + "]");
        internalConfig.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, fsUri.trim());
    }

    if (StringUtils.hasText(rmAddress)) {
        log.info("Overwriting rmAddress=[" + internalConfig.get(YarnConfiguration.RM_ADDRESS)
                + "] with rmAddress=[" + rmAddress.trim() + "]");
        internalConfig.set(YarnConfiguration.RM_ADDRESS, rmAddress.trim());
    }

    if (StringUtils.hasText(schedulerAddress)) {
        internalConfig.set(YarnConfiguration.RM_SCHEDULER_ADDRESS, schedulerAddress.trim());
    }

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

    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.squashtest.tm.web.internal.context.ReloadableSquashTmMessageSource.java

private void addPluginBasenames(Set<String> consolidatedBasenames) throws IOException {
    Resource[] resources = resourcePatternResolver
            .getResources("classpath*:org/squashtest/tm/plugin/**/messages.properties");

    for (Resource resource : resources) {
        try {/*from   ww w .jav a2  s .  com*/
            if (resource.exists()) {
                // resource path is external-path/jar-name.jar!/internal-path/messages.properties
                String path = resource.getURL().getPath();
                int bang = path.lastIndexOf('!');
                String basename = "classpath:" + StringUtils.removeEnd(path.substring(bang + 2), ".properties");
                consolidatedBasenames.add(basename);

                LOGGER.info(
                        "Registering *discovered* plugin classpath path {} as a basename for application MessageSource",
                        basename);
            }

        } catch (IOException e) {
            LOGGER.info("An IO error occurred while looking up plugin language resources '{}': {}", resource,
                    e.getMessage());
            LOGGER.debug("Plugin language resources lookup error for resource {}", resource, e);
        }
    }
}

From source file:org.squashtest.tm.web.internal.context.ReloadableSquashTmMessageSource.java

private void addExternalBasenames(Set<String> consolidatedBasenames) {
    String locationPattern = squashPathProperties.getLanguagesPath() + "/**/messages.properties";
    if (!locationPattern.startsWith("file:")) {
        locationPattern = "file:" + locationPattern;
    }//w  w  w  .ja  v  a 2 s .  co m

    try {
        Resource[] resources = resourcePatternResolver.getResources(locationPattern);

        for (Resource resource : resources) {
            if (resource.exists()) {
                String basename = StringUtils.removeEnd(resource.getURL().getPath(), ".properties");
                consolidatedBasenames.add(basename);

                LOGGER.info(
                        "Registering *discovered* external path {} as a basename for application MessageSource",
                        basename);
            }

        }
    } catch (IOException e) {
        LOGGER.info("An IO error occurred while looking up external language resources '{}' : {}",
                locationPattern, e.getMessage());
        LOGGER.debug("External language lookup error. Current path : {}", new File(".").toString(), e);
    }
}

From source file:org.squashtest.tm.web.internal.context.ReloadableSquashTmMessageSource.java

private boolean isFirstLevelDirectory(Resource resource) throws IOException {
    if (!resource.exists()) {
        return false;
    }/*from w w  w.j  ava2 s.c o  m*/

    // in runtime env we do not work with file (exception) so we have to use URLs
    URL url = resource.getURL();
    return url.getPath().endsWith(MESSAGES_BASE_PATH + resource.getFilename() + '/');
}