Java 类org.springframework.core.io.UrlResource 实例源码

项目:cas-5.1.0    文件:ChainingMetadataResolverCacheLoader.java   
/**
 * Resolve metadata from resource.
 *
 * @param service           the service
 * @param metadataResolvers the metadata resolvers
 * @throws Exception the io exception
 */
protected void resolveMetadataFromResource(final SamlRegisteredService service,
                                           final List<MetadataResolver> metadataResolvers) throws Exception {

    final String metadataLocation = service.getMetadataLocation();
    LOGGER.info("Loading SAML metadata from [{}]", metadataLocation);
    final AbstractResource metadataResource = ResourceUtils.getResourceFrom(metadataLocation);

    if (metadataResource instanceof FileSystemResource) {
        resolveFileSystemBasedMetadataResource(service, metadataResolvers, metadataResource);
    }

    if (metadataResource instanceof UrlResource) {
        resolveUrlBasedMetadataResource(service, metadataResolvers, metadataResource);
    }

    if (metadataResource instanceof ClassPathResource) {
        resolveClasspathBasedMetadataResource(service, metadataResolvers, metadataLocation, metadataResource);
    }
}
项目:Learning-Spring-Boot-2.0-Second-Edition    文件:ImageServiceTests.java   
@Test
public void findOneShouldReturnNotYetFetchedUrl() {
    // when
    Mono<Resource> image = imageService.findOneImage("alpha.jpg");

    // then
    then(image).isNotNull();

    StepVerifier.create(image)
        .expectNextMatches(resource -> {
            then(resource.getDescription()).isEqualTo("URL [file:upload-dir/alpha.jpg]");
            then(resource.exists()).isFalse();
            then(resource.getClass()).isEqualTo(UrlResource.class);
            return true;
        })
        .verifyComplete();
}
项目:file-download-upload-zip-demo    文件:FileSystemStorageService.java   
@Override
public Resource loadAsResource(String filename) {
    try {
        Path file = load(filename);
        Resource resource = new UrlResource(file.toUri());
        if(resource.exists() || resource.isReadable()) {
            return resource;
        }
        else {
            throw new StorageFileNotFoundException("Could not read file: " + filename);

        }
    } catch (MalformedURLException e) {
        throw new StorageFileNotFoundException("Could not read file: " + filename, e);
    }
}
项目:cas-5.1.0    文件:DynamicMetadataResolverAdapter.java   
@Override
protected InputStream getResourceInputStream(final Resource resource, final String entityId) throws IOException {
    if (resource instanceof UrlResource && resource.getURL().toExternalForm().toLowerCase().endsWith("/entities/")) {
        final String encodedId = EncodingUtils.urlEncode(entityId);
        final URL url = new URL(resource.getURL().toExternalForm().concat(encodedId));

        LOGGER.debug("Locating metadata input stream for [{}] via [{}]", encodedId, url);
        final HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
        httpcon.setDoOutput(true);
        httpcon.addRequestProperty("Accept", "*/*");
        httpcon.setRequestMethod("GET");
        httpcon.connect();
        return httpcon.getInputStream();
    }
    return ClosedInputStream.CLOSED_INPUT_STREAM;
}
项目:jmzTab-m    文件:FileSystemStorageService.java   
@Override
public Resource loadAsResource(UserSessionFile userSessionFile) {
    if (userSessionFile == null) {
        throw new StorageException(
            "Cannot retrieve file when userSessionFile is null!");
    }
    try {
        Path file = load(userSessionFile);
        Resource resource = new UrlResource(file.toUri());
        if (resource.exists() || resource.isReadable()) {
            return resource;
        } else {
            throw new StorageFileNotFoundException(
                "Could not read file: " + userSessionFile.getFilename());

        }
    } catch (MalformedURLException e) {
        throw new StorageFileNotFoundException(
            "Could not read file: " + userSessionFile.getFilename(), e);
    }
}
项目:gemini.blueprint    文件:OsgiBundleResourcePatternResolverTest.java   
/**
 * Test method for
 * {@link org.springframework.osgi.context.OsgiBundleResourcePatternResolver#getResources(java.lang.String)}.
 */
public void testGetResourcesString() throws Exception {
    Resource[] res;

    try {
        res = resolver.getResources("classpath*:**/*");
        fail("should have thrown exception");
    }
    catch (Exception ex) {
        // expected
    }

    String thisClass = "org/eclipse/gemini/blueprint/io/OsgiBundleResourcePatternResolverTest.class";

    res = resolver.getResources("osgibundle:" + thisClass);
    assertNotNull(res);
    assertEquals(1, res.length);
    assertTrue(res[0] instanceof UrlResource);
}
项目:FastBootWeixin    文件:MapDbWxMediaStore.java   
void fillMediaEntity(MediaEntity mediaEntity) {
    mediaEntity.setResourcePath(resourcePath);
    mediaEntity.setResourceUrl(resourceUrl);
    mediaEntity.setMediaId(mediaId);
    mediaEntity.setMediaUrl(mediaUrl);
    mediaEntity.setCreatedTime(createdTime);
    mediaEntity.setModifiedTime(modifiedTime);
    mediaEntity.setMediaType(mediaType);
    mediaEntity.setStoreType(storeType);
    if (resourcePath != null) {
        mediaEntity.setResource(new FileSystemResource(resourcePath));
    } else if (resourceUrl != null) {
        try {
            mediaEntity.setResource(new UrlResource(URI.create(resourceUrl)));
        } catch (MalformedURLException e) {
            logger.error(e.getMessage(), e);
        }
    }
}
项目:AIweb    文件:UploadServiceImpl.java   
@Override
public Resource loadAsResource(String filename) {
    try {
        Path file = this.rootLocation.resolve(filename);
        Resource resource = new UrlResource(file.toUri());
        if (resource.exists() || resource.isReadable()) {
            return resource;
        } else {
            throw new UploadFileNotFoundException(
                    "Could not read file: " + filename);

        }
    } catch (MalformedURLException e) {
        throw new UploadFileNotFoundException("Could not read file: " + filename, e);
    }
}
项目:AIweb    文件:UploadKaServiceImpl.java   
@Override
public Resource loadAsResource(String filename) {
    try {
        Path file = this.rootLocation.resolve(filename);
        Resource resource = new UrlResource(file.toUri());
        if (resource.exists() || resource.isReadable()) {
            return resource;
        } else {
            throw new UploadFileNotFoundException(
                    "Could not read file: " + filename);

        }
    } catch (MalformedURLException e) {
        throw new UploadFileNotFoundException("Could not read file: " + filename, e);
    }
}
项目:spring4-understanding    文件:SpringFactoriesLoader.java   
/**
 * Load the fully qualified class names of factory implementations of the
 * given type from {@value #FACTORIES_RESOURCE_LOCATION}, using the given
 * class loader.
 * @param factoryClass the interface or abstract class representing the factory
 * @param classLoader the ClassLoader to use for loading resources; can be
 * {@code null} to use the default
 * @see #loadFactories
 * @throws IllegalArgumentException if an error occurs while loading factory names
 */
public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
    String factoryClassName = factoryClass.getName();
    try {
        Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
                ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
        List<String> result = new ArrayList<String>();
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
            String factoryClassNames = properties.getProperty(factoryClassName);
            result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
        }
        return result;
    }
    catch (IOException ex) {
        throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() +
                "] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);
    }
}
项目:spring4-understanding    文件:BeanFactoryGenericsTests.java   
@Test
public void testGenericListProperty() throws MalformedURLException {
    DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
    RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);

    List<String> input = new ArrayList<String>();
    input.add("http://localhost:8080");
    input.add("http://localhost:9090");
    rbd.getPropertyValues().add("resourceList", input);

    bf.registerBeanDefinition("genericBean", rbd);
    GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");

    assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0));
    assertEquals(new UrlResource("http://localhost:9090"), gb.getResourceList().get(1));
}
项目:spring4-understanding    文件:BeanFactoryGenericsTests.java   
@Test
public void testGenericSetListConstructor() throws MalformedURLException {
    DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
    RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);

    Set<String> input = new HashSet<String>();
    input.add("4");
    input.add("5");
    List<String> input2 = new ArrayList<String>();
    input2.add("http://localhost:8080");
    input2.add("http://localhost:9090");
    rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
    rbd.getConstructorArgumentValues().addGenericArgumentValue(input2);

    bf.registerBeanDefinition("genericBean", rbd);
    GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");

    assertTrue(gb.getIntegerSet().contains(new Integer(4)));
    assertTrue(gb.getIntegerSet().contains(new Integer(5)));
    assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0));
    assertEquals(new UrlResource("http://localhost:9090"), gb.getResourceList().get(1));
}
项目:spring4-understanding    文件:BeanFactoryGenericsTests.java   
@Test
public void testGenericSetListConstructorWithAutowiring() throws MalformedURLException {
    DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
    bf.registerSingleton("integer1", new Integer(4));
    bf.registerSingleton("integer2", new Integer(5));
    bf.registerSingleton("resource1", new UrlResource("http://localhost:8080"));
    bf.registerSingleton("resource2", new UrlResource("http://localhost:9090"));

    RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
    rbd.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
    bf.registerBeanDefinition("genericBean", rbd);
    GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");

    assertTrue(gb.getIntegerSet().contains(new Integer(4)));
    assertTrue(gb.getIntegerSet().contains(new Integer(5)));
    assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0));
    assertEquals(new UrlResource("http://localhost:9090"), gb.getResourceList().get(1));
}
项目:spring4-understanding    文件:BeanFactoryGenericsTests.java   
@Test
public void testGenericMapResourceConstructor() throws MalformedURLException {
    DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
    RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);

    Map<String, String> input = new HashMap<String, String>();
    input.put("4", "5");
    input.put("6", "7");
    rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
    rbd.getConstructorArgumentValues().addGenericArgumentValue("http://localhost:8080");

    bf.registerBeanDefinition("genericBean", rbd);
    GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");

    assertEquals(new Integer(5), gb.getShortMap().get(new Short("4")));
    assertEquals(new Integer(7), gb.getShortMap().get(new Short("6")));
    assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0));
}
项目:spring4-understanding    文件:BeanFactoryGenericsTests.java   
@Test
public void testGenericSetListFactoryMethod() throws MalformedURLException {
    DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
    RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
    rbd.setFactoryMethodName("createInstance");

    Set<String> input = new HashSet<String>();
    input.add("4");
    input.add("5");
    List<String> input2 = new ArrayList<String>();
    input2.add("http://localhost:8080");
    input2.add("http://localhost:9090");
    rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
    rbd.getConstructorArgumentValues().addGenericArgumentValue(input2);

    bf.registerBeanDefinition("genericBean", rbd);
    GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");

    assertTrue(gb.getIntegerSet().contains(new Integer(4)));
    assertTrue(gb.getIntegerSet().contains(new Integer(5)));
    assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0));
    assertEquals(new UrlResource("http://localhost:9090"), gb.getResourceList().get(1));
}
项目:spring4-understanding    文件:BeanFactoryGenericsTests.java   
@Test
public void testGenericMapResourceFactoryMethod() throws MalformedURLException {
    DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
    RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
    rbd.setFactoryMethodName("createInstance");

    Map<String, String> input = new HashMap<String, String>();
    input.put("4", "5");
    input.put("6", "7");
    rbd.getConstructorArgumentValues().addGenericArgumentValue(input);
    rbd.getConstructorArgumentValues().addGenericArgumentValue("http://localhost:8080");

    bf.registerBeanDefinition("genericBean", rbd);
    GenericBean<?> gb = (GenericBean<?>) bf.getBean("genericBean");

    assertEquals(new Integer(5), gb.getShortMap().get(new Short("4")));
    assertEquals(new Integer(7), gb.getShortMap().get(new Short("6")));
    assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0));
}
项目:spring4-understanding    文件:DefaultListableBeanFactoryTests.java   
@Test
public void testDoubleArrayConstructorWithAutowiring() throws MalformedURLException {
    DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
    bf.registerSingleton("integer1", new Integer(4));
    bf.registerSingleton("integer2", new Integer(5));
    bf.registerSingleton("resource1", new UrlResource("http://localhost:8080"));
    bf.registerSingleton("resource2", new UrlResource("http://localhost:9090"));

    RootBeanDefinition rbd = new RootBeanDefinition(ArrayBean.class);
    rbd.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
    bf.registerBeanDefinition("arrayBean", rbd);
    ArrayBean ab = (ArrayBean) bf.getBean("arrayBean");

    assertEquals(new Integer(4), ab.getIntegerArray()[0]);
    assertEquals(new Integer(5), ab.getIntegerArray()[1]);
    assertEquals(new UrlResource("http://localhost:8080"), ab.getResourceArray()[0]);
    assertEquals(new UrlResource("http://localhost:9090"), ab.getResourceArray()[1]);
}
项目:unity    文件:FileSystemStorageService.java   
@Override
public Resource loadAsResource(final String filename) {
    try {
        Path file = load(filename);

        Resource resource = new UrlResource(file.toUri());

        if (resource.exists() || resource.isReadable()) {
            return resource;
        } else {
            throw new FileNotFoundException();
        }

    } catch (MalformedURLException | FileNotFoundException e) {
        throw new FileSystemFileNotFoundException(e.getMessage(),
                "storage.filesystem.file.readFail",
                new Object[]{filename});
    }
}
项目:puzzle    文件:PluginXmlWebApplicationContext.java   
@Override
public Resource getResource(String location) {
    Assert.notNull(location, "Location must not be null");
    if (location.startsWith("/")) {
        return getResourceByPath(location);
    }
    else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
        return new PluginClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
    }
    else {
        try {
            // Try to parse the location as a URL...
            URL url = new URL(location);
            return new UrlResource(url);
        }
        catch (MalformedURLException ex) {
            // No URL -> resolve as resource path.
            return getResourceByPath(location);
        }
    }
}
项目:alpha-umi    文件:StorageServiceImpl.java   
@Override
public Resource loadAsResource(String filename) {
    try {
        Path file = load(filename);
        Resource resource = new UrlResource(file.toUri());
        if(resource.exists() || resource.isReadable()) {
            return resource;
        }
        else {
            throw new StorageFileNotFoundException("Could not read file: " + filename);

        }
    } catch (MalformedURLException e) {
        throw new StorageFileNotFoundException("Could not read file: " + filename, e);
    }
}
项目:spring_boot    文件:FileSystemStorageService.java   
@Override
public Resource loadAsResource(String filename) {
    try {
        Path file = load(filename);
        Resource resource = new UrlResource(file.toUri());
        if(resource.exists() || resource.isReadable()) {
            return resource;
        }
        else {
            throw new StorageFileNotFoundException("Could not read file: " + filename);

        }
    } catch (MalformedURLException e) {
        throw new StorageFileNotFoundException("Could not read file: " + filename, e);
    }
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:ResourceUtils.java   
@Override
public Resource getResource(String location) {
    Assert.notNull(location, "Location must not be null");
    if (location.startsWith(CLASSPATH_URL_PREFIX)) {
        return new ClassPathResource(
                location.substring(CLASSPATH_URL_PREFIX.length()),
                getClassLoader());
    }
    else {
        if (location.startsWith(FILE_URL_PREFIX)) {
            Resource resource = this.files.getResource(location);
            return resource;
        }
        try {
            // Try to parse the location as a URL...
            URL url = new URL(location);
            return new UrlResource(url);
        }
        catch (MalformedURLException ex) {
            // No URL -> resolve as resource path.
            return getResourceByPath(location);
        }
    }
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:DevToolsSettings.java   
static DevToolsSettings load(String location) {
    try {
        DevToolsSettings settings = new DevToolsSettings();
        Enumeration<URL> urls = Thread.currentThread().getContextClassLoader()
                .getResources(location);
        while (urls.hasMoreElements()) {
            settings.add(PropertiesLoaderUtils
                    .loadProperties(new UrlResource(urls.nextElement())));
        }
        return settings;
    }
    catch (Exception ex) {
        throw new IllegalStateException("Unable to load devtools settings from "
                + "location [" + location + "]", ex);
    }
}
项目:spring    文件:SpringFactoriesLoader.java   
/**
 * Load the fully qualified class names of factory implementations of the
 * given type from {@value #FACTORIES_RESOURCE_LOCATION}, using the given
 * class loader.
 * @param factoryClass the interface or abstract class representing the factory
 * @param classLoader the ClassLoader to use for loading resources; can be
 * {@code null} to use the default
 * @see #loadFactories
 * @throws IllegalArgumentException if an error occurs while loading factory names
 */
public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
    String factoryClassName = factoryClass.getName();
    try {
        Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
                ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
        List<String> result = new ArrayList<String>();
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
            String factoryClassNames = properties.getProperty(factoryClassName);
            result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
        }
        return result;
    }
    catch (IOException ex) {
        throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() +
                "] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);
    }
}
项目:spring-boot-concourse    文件:ResourceUtils.java   
@Override
public Resource getResource(String location) {
    Assert.notNull(location, "Location must not be null");
    if (location.startsWith(CLASSPATH_URL_PREFIX)) {
        return new ClassPathResource(
                location.substring(CLASSPATH_URL_PREFIX.length()),
                getClassLoader());
    }
    else {
        if (location.startsWith(FILE_URL_PREFIX)) {
            Resource resource = this.files.getResource(location);
            return resource;
        }
        try {
            // Try to parse the location as a URL...
            URL url = new URL(location);
            return new UrlResource(url);
        }
        catch (MalformedURLException ex) {
            // No URL -> resolve as resource path.
            return getResourceByPath(location);
        }
    }
}
项目:spring-boot-concourse    文件:DevToolsSettings.java   
static DevToolsSettings load(String location) {
    try {
        DevToolsSettings settings = new DevToolsSettings();
        Enumeration<URL> urls = Thread.currentThread().getContextClassLoader()
                .getResources(location);
        while (urls.hasMoreElements()) {
            settings.add(PropertiesLoaderUtils
                    .loadProperties(new UrlResource(urls.nextElement())));
        }
        return settings;
    }
    catch (Exception ex) {
        throw new IllegalStateException("Unable to load devtools settings from "
                + "location [" + location + "]", ex);
    }
}
项目:microbbs    文件:FileSystemStorageService.java   
@Override
public Resource loadAsResource(String filename) {
    try {
        Path file = load(filename);
        Resource resource = new UrlResource(file.toUri());
        if(resource.exists() || resource.isReadable()) {
            return resource;
        }
        else {
            throw new StorageFileNotFoundException("Could not read file: " + filename);

        }
    } catch (MalformedURLException e) {
        throw new StorageFileNotFoundException("Could not read file: " + filename, e);
    }
}
项目:spring-cloud-dataflow    文件:ResourceUtils.java   
/**
 * Extracts the version from the resource. Supported resource types are {@link
 * MavenResource}, {@link DockerResource}, and {@link UrlResource}. @param resource to be
 * used. @return the version the resource. @throws
 */
public static String getResourceVersion(Resource resource) {
    Assert.notNull(resource, "resource must not be null");
    if (resource instanceof MavenResource) {
        MavenResource mavenResource = (MavenResource) resource;
        return mavenResource.getVersion();
    }
    else if (resource instanceof DockerResource) {
        DockerResource dockerResource = (DockerResource) resource;
        return formatDockerResource(dockerResource, (s, i) -> s.substring(i + 1, s.length()));
    }
    else if (resource instanceof UrlResource) {
        return getUrlResourceVersion((UrlResource) resource);
    }
    else {
        throw new IllegalArgumentException("Do not support extracting resource from Resource of type "
                + resource.getClass().getSimpleName());
    }
}
项目:spring-cloud-dataflow    文件:ResourceUtils.java   
/**
 * Extracts the string representing the resource with the version number extracted.
 * @param resource to be used.
 * @return String representation of the resource.
 */
public static String getResourceWithoutVersion(Resource resource) {
    Assert.notNull(resource, "resource must not be null");
    if (resource instanceof MavenResource) {
        MavenResource mavenResource = (MavenResource) resource;
        return String.format("maven://%s:%s",
                mavenResource.getGroupId(),
                mavenResource.getArtifactId());
    }
    else if (resource instanceof DockerResource) {
        DockerResource dockerResource = (DockerResource) resource;
        return formatDockerResource(dockerResource, (s, i) -> s.substring(0, i));
    }
    else if (resource instanceof UrlResource) {
        return getUrlResourceWithoutVersion((UrlResource) resource);
    }
    else {
        throw new IllegalArgumentException("Do not support extracting resource from Resource of type "
                + resource.getClass().getSimpleName());
    }
}
项目:FinanceAnalytics    文件:ResourceUtils.java   
/**
 * Creates a resource from a string location.
 * <p>
 * This accepts locations starting with "classpath:" or "file:".
 * It also accepts plain locations, treated as "file:".
 * 
 * @param resourceLocation  the resource location, not null
 * @param classLoader  the class loader, null defaults to {@code ClassUtils.getDefaultClassLoader()}
 * @return the resource, not null
 */
public static Resource createResource(String resourceLocation, ClassLoader classLoader) {
  ArgumentChecker.notNull(resourceLocation, "resourceLocation");
  if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
    classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
    return new ClassPathResource(resourceLocation.substring(CLASSPATH_URL_PREFIX.length()), classLoader);
  }
  if (resourceLocation.startsWith(FILE_URL_PREFIX)) {
    return new FileSystemResource(resourceLocation.substring(FILE_URL_PREFIX.length()));
  }
  try {
    URL url = new URL(resourceLocation);
    return new UrlResource(url);
  } catch (MalformedURLException ex) {
    return new FileSystemResource(resourceLocation);
  }
}
项目:FinanceAnalytics    文件:ResourceUtils.java   
/**
 * Creates a resource locator from a resource.
 * <p>
 * This converts the resource back to a string.
 * Any class loader will be lost.
 * 
 * @param resource  the resource to convert, not null
 * @return the resource locator, not null
 */
public static String toResourceLocator(Resource resource) {
  ArgumentChecker.notNull(resource, "resource");
  if (resource instanceof ClassPathResource) {
    return CLASSPATH_URL_PREFIX + ((ClassPathResource) resource).getPath();
  }
  if (resource instanceof FileSystemResource) {
    return FILE_URL_PREFIX + ((FileSystemResource) resource).getFile();
  }
  if (resource instanceof UrlResource) {
    try {
      return resource.getURL().toExternalForm();
    } catch (IOException ex) {
      throw new IllegalArgumentException("Invalid UrlResource", ex);
    }
  }
  throw new IllegalArgumentException("Unknown resource type: " + resource.getClass());
}
项目:xap-openspaces    文件:PUPathMatchingResourcePatternResolver.java   
protected Set doFindMatchingFileSystemResources(File rootDir, String subPattern) throws IOException {
    Set result = super.doFindMatchingFileSystemResources(rootDir, subPattern);
    Set actualResult = new LinkedHashSet();
    for (Object val : result) {
        if (!(val instanceof FileSystemResource)) {
            continue;
        }
        FileSystemResource fsResource = (FileSystemResource) val;
        if (fsResource.getFile() instanceof WebsterFile) {
            WebsterFile websterFile = (WebsterFile) fsResource.getFile();
            actualResult.add(new UrlResource(websterFile.toURL()));
        } else {
            actualResult.add(fsResource);
        }
    }
    return actualResult;
}
项目:contestparser    文件:ResourceUtils.java   
@Override
public Resource getResource(String location) {
    Assert.notNull(location, "Location must not be null");
    if (location.startsWith(CLASSPATH_URL_PREFIX)) {
        return new ClassPathResource(
                location.substring(CLASSPATH_URL_PREFIX.length()),
                getClassLoader());
    }
    else {
        if (location.startsWith(FILE_URL_PREFIX)) {
            Resource resource = this.files.getResource(location);
            return resource;
        }
        try {
            // Try to parse the location as a URL...
            URL url = new URL(location);
            return new UrlResource(url);
        }
        catch (MalformedURLException ex) {
            // No URL -> resolve as resource path.
            return getResourceByPath(location);
        }
    }
}
项目:micro-server    文件:SSLConfig.java   
@Bean
public static SSLProperties sslProperties() throws IOException {
    PropertiesFactoryBean factory = new PropertiesFactoryBean();
    URL url = SSLConfig.class.getClassLoader().getResource("ssl.properties");
    if (url != null) {
        Resource reource = new UrlResource(url);
        factory.setLocation(reource);
        factory.afterPropertiesSet();
        Properties properties = factory.getObject();
        return SSLProperties.builder()
                .keyStoreFile(properties.getProperty(keyStoreFile))
                .keyStorePass(properties.getProperty(keyStorePass))
                .trustStoreFile(properties.getProperty(trustStoreFile))
                .trustStorePass(properties.getProperty(trustStorePass))
                .keyStoreType(properties.getProperty(keyStoreType))
                .keyStoreProvider(properties.getProperty(keyStoreProvider))
                .trustStoreType(properties.getProperty(trustStoreType))
                .trustStoreProvider(properties.getProperty(trustStoreProvider))
                .clientAuth(properties.getProperty(clientAuth))
                .ciphers(properties.getProperty(ciphers))
                .protocol(properties.getProperty(protocol)).build();
    }
    return null;
}
项目:sdcct    文件:SdcctResourceUtils.java   
@Nullable
public static String extractPath(Resource resource, boolean fromMetaInf) {
    try {
        String resourcePath = null;

        if (resource instanceof UrlResource) {
            resourcePath = resource.getURL().toExternalForm();
        } else if (resource instanceof FileSystemResource) {
            resourcePath = ((FileSystemResource) resource).getPath();
        } else if (resource instanceof ClassPathResource) {
            resourcePath = ((ClassPathResource) resource).getPath();
        } else if (resource instanceof PathResource) {
            resourcePath = ((PathResource) resource).getPath();
        }

        return (fromMetaInf ? StringUtils.substringAfter(resourcePath, META_INF_PATH_PREFIX) : resourcePath);
    } catch (IOException ignored) {
    }

    return null;
}
项目:SecureBPMN    文件:SpringConfigurationHelper.java   
public static ProcessEngine buildProcessEngine(URL resource) {
  log.fine("==== BUILDING SPRING APPLICATION CONTEXT AND PROCESS ENGINE =========================================");

  ApplicationContext applicationContext = new GenericXmlApplicationContext(new UrlResource(resource));
  Map<String, ProcessEngine> beansOfType = applicationContext.getBeansOfType(ProcessEngine.class);
  if ( (beansOfType==null)
       || (beansOfType.isEmpty())
     ) {
    throw new ActivitiException("no "+ProcessEngine.class.getName()+" defined in the application context "+resource.toString());
  }

  ProcessEngine processEngine = beansOfType.values().iterator().next();

  log.fine("==== SPRING PROCESS ENGINE CREATED ==================================================================");
  return processEngine;
}
项目:ignite    文件:IgniteSpringHelperImpl.java   
/**
 * @param url XML file URL.
 * @return Context.
 * @throws IgniteCheckedException In case of error.
 */
private ApplicationContext initContext(URL url) throws IgniteCheckedException {
    GenericApplicationContext springCtx;

    try {
        springCtx = new GenericApplicationContext();

        new XmlBeanDefinitionReader(springCtx).loadBeanDefinitions(new UrlResource(url));

        springCtx.refresh();
    }
    catch (BeansException e) {
        if (X.hasCause(e, ClassNotFoundException.class))
            throw new IgniteCheckedException("Failed to instantiate Spring XML application context " +
                "(make sure all classes used in Spring configuration are present at CLASSPATH) " +
                "[springUrl=" + url + ']', e);
        else
            throw new IgniteCheckedException("Failed to instantiate Spring XML application context [springUrl=" +
                url + ", err=" + e.getMessage() + ']', e);
    }

    return springCtx;
}
项目:ignite    文件:IgniteSpringHelperImpl.java   
/**
 * Creates Spring application context. Optionally excluded properties can be specified,
 * it means that if such a property is found in {@link org.apache.ignite.configuration.IgniteConfiguration}
 * then it is removed before the bean is instantiated.
 * For example, {@code streamerConfiguration} can be excluded from the configs that Visor uses.
 *
 * @param cfgUrl Resource where config file is located.
 * @param excludedProps Properties to be excluded.
 * @return Spring application context.
 * @throws IgniteCheckedException If configuration could not be read.
 */
public static ApplicationContext applicationContext(URL cfgUrl, final String... excludedProps)
    throws IgniteCheckedException {
    try {
        GenericApplicationContext springCtx = prepareSpringContext(excludedProps);

        new XmlBeanDefinitionReader(springCtx).loadBeanDefinitions(new UrlResource(cfgUrl));

        springCtx.refresh();

        return springCtx;
    }
    catch (BeansException e) {
        if (X.hasCause(e, ClassNotFoundException.class))
            throw new IgniteCheckedException("Failed to instantiate Spring XML application context " +
                "(make sure all classes used in Spring configuration are present at CLASSPATH) " +
                "[springUrl=" + cfgUrl + ']', e);
        else
            throw new IgniteCheckedException("Failed to instantiate Spring XML application context [springUrl=" +
                cfgUrl + ", err=" + e.getMessage() + ']', e);
    }
}
项目:ml-javaclient-util    文件:BaseModulesFinder.java   
protected void addAssetDirectories(Modules modules, String baseDir) {
List<Resource> dirs = new ArrayList<>();

List<String> recognizedPaths = getRecognizedPaths();

// classpath needs the trailing / to find child dirs
findResources("asset module directories", baseDir, "*", "*/").stream().forEach(resource -> {
    try {
        File f = new File(resource.getURL().getFile());
        String uri = resource.getURI().toString();
        boolean isRecognized = recognizedPaths.contains(f.getName());
        // when the modules are in a jar inside a war
        boolean hasWeirdWarPath = uri.contains("jar:war");
        if (!(isRecognized || hasWeirdWarPath)) {
            boolean isDir = (resource instanceof FileSystemResource && f.isDirectory());
            boolean isUrlResource = (resource instanceof UrlResource);
            boolean notInList = dirs.indexOf(resource) < 0;
            if ((isDir || isUrlResource) && notInList) {
                dirs.add(resource);
            }
        }
    } catch (IOException e) {}
});

      modules.setAssetDirectories(dirs);
  }
项目:spring-cloud-stream    文件:BinderFactoryConfiguration.java   
@Bean
@ConditionalOnMissingBean(BinderTypeRegistry.class)
public BinderTypeRegistry binderTypeRegistry(ConfigurableApplicationContext configurableApplicationContext) {
    Map<String, BinderType> binderTypes = new HashMap<>();
    ClassLoader classLoader = configurableApplicationContext.getClassLoader();
    // the above can never be null since it will default to ClassUtils.getDefaultClassLoader(..)
    try {
        Enumeration<URL> resources = classLoader.getResources("META-INF/spring.binders");
        if (!Boolean.valueOf(this.selfContained) && (resources == null || !resources.hasMoreElements())) {
            throw new BeanCreationException("Cannot create binder factory, no `META-INF/spring.binders` " +
                    "resources found on the classpath");
        }
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            UrlResource resource = new UrlResource(url);
            for (BinderType binderType : parseBinderConfigurations(classLoader, resource)) {
                binderTypes.put(binderType.getDefaultName(), binderType);
            }
        }
    }
    catch (IOException | ClassNotFoundException e) {
        throw new BeanCreationException("Cannot create binder factory:", e);
    }
    return new DefaultBinderTypeRegistry(binderTypes);
}