下面列出了怎么用org.springframework.core.io.UrlResource的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* ファイルを読み込みます。
*
* @param location
* @param filename
* @return
*/
public Resource loadFile(Path location, String filename) {
try {
Path file = location.resolve(filename);
Resource resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
}
throw new FileNotFoundException("could not read file. " + filename);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(
"malformed Url resource. [location=" + location.toString() + ", filename=" + filename + "]", e);
}
}
@Override
public FileSource child(String subDirectoryName) {
List<FileSource> childSources = new ArrayList<>();
for (FileSource resource : this.sources) {
try {
UrlResource uri = new UrlResource(
resource.child(subDirectoryName).getUri());
if (uri.createRelative(subDirectoryName).exists()) {
childSources.add(resource.child(subDirectoryName));
}
}
catch (IOException e) {
// Ignore
}
}
if (!childSources.isEmpty()) {
return new ResourcesFileSource(childSources.toArray(new FileSource[0]));
}
return this.sources[0].child(subDirectoryName);
}
@Test
public void testGenericMapResourceConstructor() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
Map<String, String> input = new HashMap<>();
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));
}
@Test
public void testGenericSetListFactoryMethod() throws Exception {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
rbd.setFactoryMethodName("createInstance");
Set<String> input = new HashSet<>();
input.add("4");
input.add("5");
List<String> input2 = new ArrayList<>();
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));
}
@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));
}
@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]);
}
@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));
}
/**
* 配置文件信息获取
*
* @return
*/
@Override
public Map<String, Object> defaultConfig() {
Map<String, Object> rtnMap = new HashMap<>(1);
try {
ClassLoader classLoader = this.getClass().getClassLoader();
Enumeration<URL> urls = (classLoader != null ?
classLoader.getResources(getPropFilePath()) :
ClassLoader.getSystemResources(getPropFilePath()));
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
UrlResource resource = new UrlResource(url);
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
for (Map.Entry<?, ?> entry : properties.entrySet()) {
rtnMap.put((String) entry.getKey(), entry.getValue());
}
}
} catch (IOException e) {
log.error("加载初始配置错误.", e);
}
return rtnMap;
}
private ResourceSource getResourceSource(Resource resource) {
ResourceSource source=null;
if(resource instanceof ClassPathResource) {
source=ResourceSource.CLASSPATH;
} else if(resource instanceof UrlResource) {
source=ResourceSource.REMOTE;
} else if(resource instanceof FileSystemResource) {
source=ResourceSource.FILE_SYSTEM;
} else if(resource instanceof InputStreamResource) {
source=ResourceSource.STREAM;
} else if(resource instanceof ByteArrayResource) {
source=ResourceSource.RAW;
} else {
String type=resource.getClass().toString();
if(CLAZZ_NAME.equals(type)) {
source=ResourceSource.OSGI_BUNDLE;
} else {
source=ResourceSource.UNKNOWN;
}
}
return source;
}
@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 FileNotFoundException(
"Could not read file: " + filename);
}
}
catch (MalformedURLException e) {
throw new FileNotFoundException("Could not read file: " + filename, e);
}
}
/**
* Launch an application in a separate JVM.
* @param clz the main class to launch
* @param properties the properties to pass to the application
* @param args the command line arguments for the application
* @return a string identifier for the application
*/
private String launchApplication(Class<?> clz, Map<String, String> properties,
List<String> args) {
Resource resource = new UrlResource(
clz.getProtectionDomain().getCodeSource().getLocation());
properties.put(AppDeployer.GROUP_PROPERTY_KEY, "test-group");
properties.put("main", clz.getName());
properties.put("classpath", System.getProperty("java.class.path"));
String appName = String.format("%s-%s", clz.getSimpleName(),
properties.get("server.port"));
AppDefinition definition = new AppDefinition(appName, properties);
AppDeploymentRequest request = new AppDeploymentRequest(definition, resource,
properties, args);
return this.deployer.deploy(request);
}
@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]);
}
@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;
}
/**
* 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);
}
}
@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);
}
}
@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]);
}
public static DmnEngine buildDmnEngine(URL resource) {
LOGGER.debug("==== BUILDING SPRING APPLICATION CONTEXT AND DMN ENGINE =========================================");
try (GenericXmlApplicationContext applicationContext = new GenericXmlApplicationContext(new UrlResource(resource))) {
Map<String, DmnEngine> beansOfType = applicationContext.getBeansOfType(DmnEngine.class);
if ((beansOfType == null) || beansOfType.isEmpty()) {
throw new FlowableException("no " + DmnEngine.class.getName() + " defined in the application context " + resource);
}
DmnEngine dmnEngine = beansOfType.values().iterator().next();
LOGGER.debug("==== SPRING DMN ENGINE CREATED ==================================================================");
return dmnEngine;
}
}
@Override
public BinaryFile getBinaryFileNamed(String name) {
for (FileSource resource : this.sources) {
try {
UrlResource uri = new UrlResource(resource.getUri());
if (uri.exists()) {
return resource.getBinaryFileNamed(name);
}
}
catch (IOException e) {
// Ignore
}
}
throw new IllegalStateException("Cannot create file for " + name);
}
@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 {
return null;
}
} catch (MalformedURLException e) {
logger.error(e.getMessage(), e);
return null;
}
}
@Override
public Resource loadAsResource(String keyName) {
try {
URL url = new URL(generateUrl(keyName));
Resource resource = new UrlResource(url);
if (resource.exists() || resource.isReadable()) {
return resource;
}
} catch (MalformedURLException e) {
logger.error(e.getMessage(), e);
}
return null;
}
public static IdmEngine buildIdmEngine(URL resource) {
LOGGER.debug("==== BUILDING SPRING APPLICATION CONTEXT AND IDM ENGINE =========================================");
ApplicationContext applicationContext = new GenericXmlApplicationContext(new UrlResource(resource));
Map<String, IdmEngine> beansOfType = applicationContext.getBeansOfType(IdmEngine.class);
if ((beansOfType == null) || beansOfType.isEmpty()) {
throw new FlowableException("no " + IdmEngine.class.getName() + " defined in the application context " + resource);
}
IdmEngine idmEngine = beansOfType.values().iterator().next();
LOGGER.debug("==== SPRING IDM ENGINE CREATED ==================================================================");
return idmEngine;
}
public static ProcessEngine buildProcessEngine(URL resource) {
log.debug("==== 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.debug("==== SPRING PROCESS ENGINE CREATED ==================================================================");
return processEngine;
}
private boolean isResourceUnderLocation(Resource resource, Resource location) throws IOException {
if (resource.getClass() != location.getClass()) {
return false;
}
String resourcePath;
String locationPath;
if (resource instanceof UrlResource) {
resourcePath = resource.getURL().toExternalForm();
locationPath = StringUtils.cleanPath(location.getURL().toString());
}
else if (resource instanceof ClassPathResource) {
resourcePath = ((ClassPathResource) resource).getPath();
locationPath = StringUtils.cleanPath(((ClassPathResource) location).getPath());
}
else {
resourcePath = resource.getURL().getPath();
locationPath = StringUtils.cleanPath(location.getURL().getPath());
}
if (locationPath.equals(resourcePath)) {
return true;
}
locationPath = (locationPath.endsWith("/") || locationPath.isEmpty() ? locationPath : locationPath + "/");
return (resourcePath.startsWith(locationPath) && !isInvalidEncodedPath(resourcePath));
}
private boolean isResourceUnderLocation(Resource resource) throws IOException {
if (resource.getClass() != this.location.getClass()) {
return false;
}
String resourcePath;
String locationPath;
if (resource instanceof UrlResource) {
resourcePath = resource.getURL().toExternalForm();
locationPath = StringUtils.cleanPath(this.location.getURL().toString());
}
else if (resource instanceof ClassPathResource) {
resourcePath = ((ClassPathResource) resource).getPath();
locationPath = StringUtils.cleanPath(((ClassPathResource) this.location).getPath());
}
else {
resourcePath = resource.getURL().getPath();
locationPath = StringUtils.cleanPath(this.location.getURL().getPath());
}
if (locationPath.equals(resourcePath)) {
return true;
}
locationPath = (locationPath.endsWith("/") || locationPath.isEmpty() ? locationPath : locationPath + "/");
if (!resourcePath.startsWith(locationPath)) {
return false;
}
if (resourcePath.contains("%") && StringUtils.uriDecode(resourcePath, StandardCharsets.UTF_8).contains("../")) {
return false;
}
return true;
}
@Test // SPR-12624
public void checkRelativeLocation() throws Exception {
String locationUrl= new UrlResource(getClass().getResource("./test/")).getURL().toExternalForm();
Resource location = new UrlResource(locationUrl.replace("/springframework","/../org/springframework"));
List<Resource> locations = singletonList(location);
assertNotNull(this.resolver.resolveResource(null, "main.css", locations, null).block(TIMEOUT));
}
@Test
public void deployHttpArtifactShouldDelete() throws IOException, URISyntaxException {
UrlResource resource = mock(UrlResource.class);
folder.newFolder("download");
File downloadedArtifact = folder.newFile("download/artifact.jar");
given(resource.getFile()).willReturn(downloadedArtifact);
given(resource.getURI()).willReturn(new URI("http://somehost/artifact.jar"));
assertTrue(this.deploymentProperties.isAutoDeleteMavenArtifacts());
deployResource(this.deployer, resource);
assertFalse(downloadedArtifact.exists());
}
@Override
public Resource loadAsResource(Path fullPath) throws FileNotFoundException {
try {
Resource resource = new UrlResource(fullPath.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
throw new FileNotFoundException(
"Could not read file: " + fullPath);
}
} catch (MalformedURLException e) {
throw new FileNotFoundException("Could not read file: " + fullPath);
}
}
@Test
public void testSignificantLoad() throws Exception {
Assume.group(TestGroup.LONG_RUNNING);
// the biggest public class in the JDK (>60k)
URL url = getClass().getResource("/java/awt/Component.class");
assertThat(url, notNullValue());
// look at a LOT of items
for (int i = 0; i < ITEMS_TO_LOAD; i++) {
Resource resource = new UrlResource(url) {
@Override
public boolean equals(Object obj) {
return (obj == this);
}
@Override
public int hashCode() {
return System.identityHashCode(this);
}
};
MetadataReader reader = mrf.getMetadataReader(resource);
assertThat(reader, notNullValue());
}
// useful for profiling to take snapshots
// System.in.read();
}
private static File getFile(UrlResource file) {
try {
return file.getFile();
}
catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Test
void initializeRemoteConfig() throws Exception {
InitializrMetadata localMetadata = this.metadataProvider.get();
InitializrMetadata metadata = InitializrMetadataBuilder.create()
.withInitializrMetadata(new UrlResource(createUrl("/metadata/config"))).build();
// Basic assertions
assertThat(metadata.getDependencies().getContent()).hasSameSizeAs(localMetadata.getDependencies().getContent());
assertThat(metadata.getTypes().getContent()).hasSameSizeAs(localMetadata.getTypes().getContent());
assertThat(metadata.getBootVersions().getContent()).hasSameSizeAs(localMetadata.getBootVersions().getContent());
assertThat(metadata.getPackagings().getContent()).hasSameSizeAs(localMetadata.getPackagings().getContent());
assertThat(metadata.getJavaVersions().getContent()).hasSameSizeAs(localMetadata.getJavaVersions().getContent());
assertThat(metadata.getLanguages().getContent()).hasSameSizeAs(localMetadata.getLanguages().getContent());
}