Add support for binary file server via context negotation

If client sends "Accept: application/octet-stream" then the server
sends back a binary file (no placeholders and no text conversion)
This commit is contained in:
Dave Syer
2015-10-06 17:58:02 +01:00
parent 274c7cff49
commit c0ddcd800e
2 changed files with 22 additions and 2 deletions

View File

@@ -26,6 +26,7 @@ import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
@@ -76,6 +77,20 @@ public class ResourceController {
return environment.resolvePlaceholders(text).replace("$_{", "${");
}
@RequestMapping(value="/{name}/{profile}/{label}/{path:.*}", produces=MediaType.APPLICATION_OCTET_STREAM_VALUE)
public synchronized byte[] binary(@PathVariable String name,
@PathVariable String profile, @PathVariable String label,
@PathVariable String path) throws IOException {
StandardEnvironment environment = new StandardEnvironment();
environment.getPropertySources().addAfter(
StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME,
new EnvironmentPropertySource(
this.environmentRepository.findOne(name, profile, label)));
byte[] text = StreamUtils.copyToByteArray(
this.resourceRepository.findOne(name, profile, label, path).getInputStream());
return text;
}
@ExceptionHandler(NoSuchResourceException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public void notFound(NoSuchResourceException e) {

View File

@@ -24,8 +24,6 @@ import org.junit.Test;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.config.server.environment.NativeEnvironmentRepository;
import org.springframework.cloud.config.server.environment.NativeEnvironmentRepositoryTests;
import org.springframework.cloud.config.server.resource.GenericResourceRepository;
import org.springframework.cloud.config.server.resource.ResourceController;
import org.springframework.context.ConfigurableApplicationContext;
/**
@@ -66,6 +64,13 @@ public class ResourceControllerTests {
assertEquals("{\n \"foo\": \"dev_bar\"\n}", resource);
}
@Test
public void templateReplacementNotForBinary() throws Exception {
this.environmentRepository.setSearchLocations("classpath:/test");
String resource = new String(this.controller.binary("foo", "bar", "dev", "template.json"));
assertEquals("{\n \"foo\": \"${foo}\"\n}", resource);
}
@Test
public void escapedPlaceholder() throws Exception {
this.environmentRepository.setSearchLocations("classpath:/test");