Skip to content

Commit

Permalink
Filter non-existing static resource locations
Browse files Browse the repository at this point in the history
  • Loading branch information
rstoyanchev committed Oct 12, 2021
1 parent 5bd9053 commit a2c52a9
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
Expand Up @@ -25,6 +25,7 @@
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
Expand Down Expand Up @@ -424,6 +425,7 @@ public void afterPropertiesSet() throws Exception {
}

private void resolveResourceLocations() {
List<Resource> result = new ArrayList<>();
if (!this.locationValues.isEmpty()) {
ApplicationContext applicationContext = obtainApplicationContext();
for (String location : this.locationValues) {
Expand Down Expand Up @@ -452,7 +454,7 @@ private void resolveResourceLocations() {
"but resolved to a Resource of type: " + resource.getClass() + ". " +
"If this is intentional, please pass it as a pre-configured Resource via setLocations.");
}
this.locationsToUse.add(resource);
result.add(resource);
if (charset != null) {
if (!(resource instanceof UrlResource)) {
throw new IllegalArgumentException("Unexpected charset for non-UrlResource: " + resource);
Expand All @@ -461,7 +463,11 @@ private void resolveResourceLocations() {
}
}
}
this.locationsToUse.addAll(this.locationResources);

result.addAll(this.locationResources);
result = result.stream().filter(Resource::exists).collect(Collectors.toList());

this.locationsToUse.addAll(result);
}

/**
Expand Down
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -312,6 +312,24 @@ public String getMimeType(String filePath) {
assertThat(this.response.getContentAsString()).isEqualTo("h1 { color:red; }");
}

@Test // gh-27538
public void filterNonExistingLocations() throws Exception {
List<Resource> inputLocations = Arrays.asList(
new ClassPathResource("test/", getClass()),
new ClassPathResource("testalternatepath/", getClass()),
new ClassPathResource("nosuchpath/", getClass()));

ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler();
handler.setServletContext(new MockServletContext());
handler.setLocations(inputLocations);
handler.afterPropertiesSet();

List<Resource> actual = handler.getLocations();
assertThat(actual).hasSize(2);
assertThat(actual.get(0).getURL().toString()).endsWith("test/");
assertThat(actual.get(1).getURL().toString()).endsWith("testalternatepath/");
}

@Test
public void testInvalidPath() throws Exception {

Expand Down

0 comments on commit a2c52a9

Please sign in to comment.