Deprecated as of 4.3.13, in favor of selective use of ClassPathResource.ClassPathResource(String, ClassLoader) vs ClassPathResource.ClassPathResource(String, Class)
Refine search
public @Bean Jackson2RepositoryPopulatorFactoryBean repositoryPopulator() { Jackson2RepositoryPopulatorFactoryBean factoryBean = new Jackson2RepositoryPopulatorFactoryBean(); factoryBean.setResources(new Resource[] { new ClassPathResource("spring-blog.atom.json") }); return factoryBean; }
ClassPathResource resource = new ClassPathResource( "app.properties" ); p = new Properties(); InputStream inputStream = null; try { inputStream = resource.getInputStream(); cloudProperties.load( inputStream ); } catch ( IOException e ) { LOGGER.error( e.getMessage(), e ); } finally { Closeables.closeQuietly( inputStream ); }
private long resourceLastModified(String resourceName) throws IOException { return new ClassPathResource(resourceName, getClass()).getFile().lastModified(); }
ClassPathResource cpr = new ClassPathResource("folder/file.xsd"); InputStream is = cpr.getInputStream();
@Test public void testJobParametersResolution() { Properties jobParameters = new Properties(); jobParameters.setProperty("jobParameter1", "myfile.txt"); jobParameters.setProperty("jobParameter2", "#{jobProperties['jobProperty2']}"); jobParameters.setProperty("jobParameter3", "#{jobParameters['jobParameter1']}"); @SuppressWarnings("resource") JsrXmlApplicationContext applicationContext = new JsrXmlApplicationContext(jobParameters); applicationContext.setValidating(false); applicationContext.load(new ClassPathResource("jsrBaseContext.xml"), new ClassPathResource("/META-INF/batch.xml"), new ClassPathResource("/META-INF/batch-jobs/jsrPropertyPreparseTestJob.xml")); applicationContext.refresh(); Document document = getDocument("/META-INF/batch-jobs/jsrPropertyPreparseTestJob.xml"); JsrBeanDefinitionDocumentReader documentReader = new JsrBeanDefinitionDocumentReader(applicationContext); documentReader.initProperties(document.getDocumentElement()); Properties resolvedParameters = documentReader.getJobParameters(); assertNotNull(resolvedParameters); assertTrue("Wrong number of job parameters", resolvedParameters.size() == 3); assertEquals("myfile.txt", resolvedParameters.getProperty("jobParameter1")); assertEquals("jobProperty1Value", resolvedParameters.getProperty("jobParameter2")); assertEquals("myfile.txt", resolvedParameters.getProperty("jobParameter3")); }
@SuppressWarnings("resource") @Test public void testGenerationOfBeanDefinitionsForMultipleReferences() throws Exception { JsrXmlApplicationContext applicationContext = new JsrXmlApplicationContext(new Properties()); applicationContext.setValidating(false); applicationContext.load(new ClassPathResource("jsrBaseContext.xml"), new ClassPathResource("/META-INF/batch.xml"), new ClassPathResource("/META-INF/batch-jobs/jsrUniqueInstanceTests.xml")); applicationContext.refresh(); assertTrue("exitStatusSettingStepListener bean definition not found", applicationContext.containsBeanDefinition("exitStatusSettingStepListener")); assertTrue("exitStatusSettingStepListener1 bean definition not found", applicationContext.containsBeanDefinition("exitStatusSettingStepListener1")); assertTrue("exitStatusSettingStepListener2 bean definition not found", applicationContext.containsBeanDefinition("exitStatusSettingStepListener2")); assertTrue("exitStatusSettingStepListener3 bean definition not found", applicationContext.containsBeanDefinition("exitStatusSettingStepListener3")); assertTrue("exitStatusSettingStepListenerClassBeanDefinition bean definition not found", applicationContext.containsBeanDefinition("org.springframework.batch.core.jsr.step.listener.ExitStatusSettingStepListener")); assertTrue("exitStatusSettingStepListener1ClassBeanDefinition bean definition not found", applicationContext.containsBeanDefinition("org.springframework.batch.core.jsr.step.listener.ExitStatusSettingStepListener1")); assertTrue("exitStatusSettingStepListener2ClassBeanDefinition bean definition not found", applicationContext.containsBeanDefinition("org.springframework.batch.core.jsr.step.listener.ExitStatusSettingStepListener2")); assertTrue("exitStatusSettingStepListener3ClassBeanDefinition bean definition not found", applicationContext.containsBeanDefinition("org.springframework.batch.core.jsr.step.listener.ExitStatusSettingStepListener3")); assertTrue("testBatchlet bean definition not found", applicationContext.containsBeanDefinition("testBatchlet")); assertTrue("testBatchlet1 bean definition not found", applicationContext.containsBeanDefinition("testBatchlet1")); }
private static List<HandlerMapping> initFallback(ApplicationContext applicationContext) { Properties props; String path = "DispatcherServlet.properties"; try { Resource resource = new ClassPathResource(path, DispatcherServlet.class); props = PropertiesLoaderUtils.loadProperties(resource); } catch (IOException ex) { throw new IllegalStateException("Could not load '" + path + "': " + ex.getMessage()); } String value = props.getProperty(HandlerMapping.class.getName()); String[] names = StringUtils.commaDelimitedListToStringArray(value); List<HandlerMapping> result = new ArrayList<>(names.length); for (String name : names) { try { Class<?> clazz = ClassUtils.forName(name, DispatcherServlet.class.getClassLoader()); Object mapping = applicationContext.getAutowireCapableBeanFactory().createBean(clazz); result.add((HandlerMapping) mapping); } catch (ClassNotFoundException ex) { throw new IllegalStateException("Could not find default HandlerMapping [" + name + "]"); } } return result; }
assertEquals(new ClassPathResource("order.jar").getURL(), pu1.getJarFileUrls().get(0)); assertEquals(2, props.keySet().size()); assertEquals("on", props.getProperty("com.acme.persistence.sql-logging")); assertEquals("bar", props.getProperty("foo"));
@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 { System.getProperties().remove("logfile"); } }
@Test public void testExample3() throws Exception { PersistenceUnitReader reader = new PersistenceUnitReader( new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup()); String resource = "/org/springframework/orm/jpa/persistence-example3.xml"; PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource); assertNotNull(info); assertEquals(1, info.length); assertEquals("OrderManagement3", info[0].getPersistenceUnitName()); assertEquals(2, info[0].getJarFileUrls().size()); assertEquals(new ClassPathResource("order.jar").getURL(), info[0].getJarFileUrls().get(0)); assertEquals(new ClassPathResource("order-supplemental.jar").getURL(), info[0].getJarFileUrls().get(1)); assertEquals(0, info[0].getProperties().keySet().size()); assertNull(info[0].getJtaDataSource()); assertNull(info[0].getNonJtaDataSource()); assertFalse("Exclude unlisted should default false in 1.0.", info[0].excludeUnlistedClasses()); }
static void createGzippedFile(String filePath) throws IOException { Resource location = new ClassPathResource("test/", EncodedResourceResolverTests.class); Resource resource = new FileSystemResource(location.createRelative(filePath).getFile()); Path gzFilePath = Paths.get(resource.getFile().getAbsolutePath() + ".gz"); Files.deleteIfExists(gzFilePath); File gzFile = Files.createFile(gzFilePath).toFile(); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(gzFile)); FileCopyUtils.copy(resource.getInputStream(), out); gzFile.deleteOnExit(); }
@Test public void mixedInNulls() throws Exception { List<Resource> resources = new ArrayList<>(); resources.add(new ClassPathResource("test")); resources.add(null); resources.add(new FileSystemResource("test")); resources.add(new TestResource()); TypeDescriptor sourceType = TypeDescriptor.forObject(resources); assertSame(resources, conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources")))); }
@Override public InputSource resolveEntity(String publicId, String systemId) throws IOException { InputSource source = super.resolveEntity(publicId, systemId); if (source == null) { Resource resource = new ClassPathResource(TEST_XSD); source = new InputSource(resource.getInputStream()); source.setPublicId(publicId); source.setSystemId(systemId); } return source; } }
@Test public void testLoadNonExistentResource() { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResolutionMethod(ResolutionMethod.OVERRIDE_AND_IGNORE); factory.setResources(new ClassPathResource("no-such-file.yml")); Properties properties = factory.getObject(); assertThat(properties.size(), equalTo(0)); }
@Test public void resolveFromClasspathRoot() { Resource location = new ClassPathResource("/"); String requestPath = "org/springframework/web/servlet/resource/test/bar.css"; Resource actual = this.resolver.resolveResource(null, requestPath, Collections.singletonList(location), null); assertNotNull(actual); }
private SqlSessionFactory buildSqlSessionFactory() throws IOException { SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder(); Configuration baseConfiguration = new XMLConfigBuilder(configLocation.getInputStream()).parse(); String ibatisConfigXmlLocation = databaseStrategy.getIbatisConfigXmlLocation(); if (isNotBlank(ibatisConfigXmlLocation)) { XMLConfigBuilder builder = new XMLConfigBuilder(new ClassPathResource(ibatisConfigXmlLocation).getInputStream()); // hacky way to "inject" a previous configuration Field configurationField = ReflectionUtils.findField(XMLConfigBuilder.class, "configuration"); ReflectionUtils.makeAccessible(configurationField); ReflectionUtils.setField(configurationField, builder, baseConfiguration); baseConfiguration = builder.parse(); } baseConfiguration.setEnvironment(new Environment(getClass().getSimpleName(), new SpringManagedTransactionFactory(), this.dataSource)); return factoryBuilder.build(baseConfiguration); }
@Test public void composeResourceLookupFunction() throws Exception { ClassPathResource defaultResource = new ClassPathResource("response.txt", getClass()); Function<ServerRequest, Mono<Resource>> lookupFunction = new PathResourceLookupFunction("/resources/**", new ClassPathResource("org/springframework/web/reactive/function/server/")); Function<ServerRequest, Mono<Resource>> customLookupFunction = lookupFunction.andThen(resourceMono -> resourceMono .switchIfEmpty(Mono.just(defaultResource))); MockServerRequest request = MockServerRequest.builder() .uri(new URI("http://localhost/resources/foo")) .build(); Mono<Resource> result = customLookupFunction.apply(request); StepVerifier.create(result) .expectNextMatches(resource -> { try { return defaultResource.getFile().equals(resource.getFile()); } catch (IOException ex) { return false; } }) .expectComplete() .verify(); }
@Test public void directoryNotReadable() { Resource fileDir = new ClassPathResource("org/springframework/core"); assertTrue(fileDir.exists()); assertFalse(fileDir.isReadable()); Resource jarDir = new ClassPathResource("reactor/core"); assertTrue(jarDir.exists()); assertFalse(jarDir.isReadable()); }
@Test public void unmarshalFile() throws IOException { Resource resource = new ClassPathResource("jaxb2.xml", getClass()); File file = resource.getFile(); Flights f = (Flights) unmarshaller.unmarshal(new StreamSource(file)); testFlights(f); }
public static Properties getProperties(String propertyFile) { try { Resource resource = new FileSystemResource(propertyFile); if (!resource.exists()) { resource = new ClassPathResource(propertyFile); } return PropertiesLoaderUtils.loadProperties(resource); } catch (Exception ignored) { return null; } }