Search in sources :

Example 81 with ResourceLoader

use of org.springframework.core.io.ResourceLoader in project grails-core by grails.

the class ClosureClassIgnoringComponentScanBeanDefinitionParser method configureScanner.

@Override
protected ClassPathBeanDefinitionScanner configureScanner(ParserContext parserContext, Element element) {
    final ClassPathBeanDefinitionScanner scanner = super.configureScanner(parserContext, element);
    final ResourceLoader originalResourceLoader = parserContext.getReaderContext().getResourceLoader();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Scanning only this classloader:" + originalResourceLoader.getClassLoader());
    }
    ResourceLoader parentOnlyResourceLoader;
    try {
        parentOnlyResourceLoader = new ResourceLoader() {

            ClassLoader parentOnlyGetResourcesClassLoader = new ParentOnlyGetResourcesClassLoader(originalResourceLoader.getClassLoader());

            public Resource getResource(String location) {
                return originalResourceLoader.getResource(location);
            }

            public ClassLoader getClassLoader() {
                return parentOnlyGetResourcesClassLoader;
            }
        };
    } catch (Throwable t) {
        // restrictive classloading environment, use the original
        parentOnlyResourceLoader = originalResourceLoader;
    }
    final PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(parentOnlyResourceLoader) {

        @Override
        protected Resource[] findAllClassPathResources(String location) throws IOException {
            Set<Resource> result = new LinkedHashSet<Resource>(16);
            if (BuildSettings.CLASSES_DIR != null) {
                @SuppressWarnings("unused") URL classesDir = BuildSettings.CLASSES_DIR.toURI().toURL();
                // only scan classes from project classes directory
                String path = location;
                if (path.startsWith("/")) {
                    path = path.substring(1);
                }
                Enumeration<URL> resourceUrls = getClassLoader().getResources(path);
                while (resourceUrls.hasMoreElements()) {
                    URL url = resourceUrls.nextElement();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Scanning URL " + url.toExternalForm() + " while searching for '" + location + "'");
                    }
                    /*
                    if (!warDeployed && classesDir!= null && url.equals(classesDir)) {
                        result.add(convertClassLoaderURL(url));
                    }
                    else if (warDeployed) {
                        result.add(convertClassLoaderURL(url));
                    }
                    */
                    result.add(convertClassLoaderURL(url));
                }
            }
            return result.toArray(new Resource[result.size()]);
        }
    };
    resourceResolver.setPathMatcher(new AntPathMatcher() {

        @Override
        public boolean match(String pattern, String path) {
            if (path.endsWith(".class")) {
                String filename = GrailsStringUtils.getFileBasename(path);
                if (filename.contains("$"))
                    return false;
            }
            return super.match(pattern, path);
        }
    });
    scanner.setResourceLoader(resourceResolver);
    return scanner;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ResourceLoader(org.springframework.core.io.ResourceLoader) Resource(org.springframework.core.io.Resource) URL(java.net.URL) ClassPathBeanDefinitionScanner(org.springframework.context.annotation.ClassPathBeanDefinitionScanner) PathMatchingResourcePatternResolver(org.springframework.core.io.support.PathMatchingResourcePatternResolver) AntPathMatcher(org.springframework.util.AntPathMatcher)

Example 82 with ResourceLoader

use of org.springframework.core.io.ResourceLoader in project spring-boot by spring-projects.

the class OnResourceCondition method getMatchOutcome.

@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
    MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes(ConditionalOnResource.class.getName(), true);
    ResourceLoader loader = context.getResourceLoader();
    List<String> locations = new ArrayList<>();
    collectValues(locations, attributes.get("resources"));
    Assert.isTrue(!locations.isEmpty(), "@ConditionalOnResource annotations must specify at least one resource location");
    List<String> missing = new ArrayList<>();
    for (String location : locations) {
        String resource = context.getEnvironment().resolvePlaceholders(location);
        if (!loader.getResource(resource).exists()) {
            missing.add(location);
        }
    }
    if (!missing.isEmpty()) {
        return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnResource.class).didNotFind("resource", "resources").items(Style.QUOTE, missing));
    }
    return ConditionOutcome.match(ConditionMessage.forCondition(ConditionalOnResource.class).found("location", "locations").items(locations));
}
Also used : ResourceLoader(org.springframework.core.io.ResourceLoader) ArrayList(java.util.ArrayList)

Example 83 with ResourceLoader

use of org.springframework.core.io.ResourceLoader in project spring-boot by spring-projects.

the class SpringApplicationTests method customResourceLoader.

@Test
void customResourceLoader() {
    TestSpringApplication application = new TestSpringApplication(ExampleConfig.class);
    application.setWebApplicationType(WebApplicationType.NONE);
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    application.setResourceLoader(resourceLoader);
    this.context = application.run();
    then(application.getLoader()).should().setResourceLoader(resourceLoader);
}
Also used : ResourceLoader(org.springframework.core.io.ResourceLoader) DefaultResourceLoader(org.springframework.core.io.DefaultResourceLoader) DefaultResourceLoader(org.springframework.core.io.DefaultResourceLoader) Test(org.junit.jupiter.api.Test)

Example 84 with ResourceLoader

use of org.springframework.core.io.ResourceLoader in project spring-boot by spring-projects.

the class ConfigDataEnvironmentPostProcessorIntegrationTests method runWhenUsingCustomResourceLoader.

@Test
void runWhenUsingCustomResourceLoader() {
    this.application.setResourceLoader(new ResourceLoader() {

        @Override
        public Resource getResource(String location) {
            if (location.equals("classpath:/custom.properties")) {
                return new ByteArrayResource("the.property: fromcustom".getBytes(), location);
            }
            return new ClassPathResource("doesnotexist");
        }

        @Override
        public ClassLoader getClassLoader() {
            return getClass().getClassLoader();
        }
    });
    ConfigurableApplicationContext context = this.application.run("--spring.config.name=custom");
    String property = context.getEnvironment().getProperty("the.property");
    assertThat(property).isEqualTo("fromcustom");
}
Also used : ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) ResourceLoader(org.springframework.core.io.ResourceLoader) ClassPathResource(org.springframework.core.io.ClassPathResource) ByteArrayResource(org.springframework.core.io.ByteArrayResource) Resource(org.springframework.core.io.Resource) ByteArrayResource(org.springframework.core.io.ByteArrayResource) ClassPathResource(org.springframework.core.io.ClassPathResource) Test(org.junit.jupiter.api.Test)

Example 85 with ResourceLoader

use of org.springframework.core.io.ResourceLoader in project spring-boot by spring-projects.

the class SpringApplicationBuilderTests method customApplicationWithResourceLoader.

@Test
void customApplicationWithResourceLoader() {
    ResourceLoader resourceLoader = mock(ResourceLoader.class);
    SpringApplicationBuilder applicationBuilder = new SpringApplicationBuilder(resourceLoader, ExampleConfig.class) {

        @Override
        protected SpringApplication createSpringApplication(ResourceLoader resourceLoader, Class<?>... sources) {
            return new CustomSpringApplication(resourceLoader, sources);
        }
    };
    SpringApplication application = applicationBuilder.build();
    assertThat(application).asInstanceOf(InstanceOfAssertFactories.type(CustomSpringApplication.class)).satisfies((customApp) -> assertThat(customApp.resourceLoader).isEqualTo(resourceLoader));
}
Also used : DefaultResourceLoader(org.springframework.core.io.DefaultResourceLoader) ResourceLoader(org.springframework.core.io.ResourceLoader) SpringApplication(org.springframework.boot.SpringApplication) Test(org.junit.jupiter.api.Test)

Aggregations

ResourceLoader (org.springframework.core.io.ResourceLoader)90 Resource (org.springframework.core.io.Resource)51 Test (org.junit.Test)35 ClassRelativeResourceLoader (org.springframework.core.io.ClassRelativeResourceLoader)34 File (java.io.File)33 DefaultResourceLoader (org.springframework.core.io.DefaultResourceLoader)26 Test (org.junit.jupiter.api.Test)15 IOException (java.io.IOException)9 Environment (org.springframework.core.env.Environment)9 ByteArrayResource (org.springframework.core.io.ByteArrayResource)7 DefaultListableBeanFactory (org.springframework.beans.factory.support.DefaultListableBeanFactory)6 FileSystemResource (org.springframework.core.io.FileSystemResource)6 HashMap (java.util.HashMap)5 Configuration (freemarker.template.Configuration)4 Template (freemarker.template.Template)4 InputStream (java.io.InputStream)4 GenericApplicationContext (org.springframework.context.support.GenericApplicationContext)4 InputStreamReader (java.io.InputStreamReader)3 Properties (java.util.Properties)3 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)3