Skip to content

Instantly share code, notes, and snippets.

@efenderbosch
Created February 10, 2015 14:52
Show Gist options
  • Save efenderbosch/c66f78fc5f7c1318ffe0 to your computer and use it in GitHub Desktop.
Save efenderbosch/c66f78fc5f7c1318ffe0 to your computer and use it in GitHub Desktop.
Ngnix Config Controller
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.config.Environment;
import org.springframework.cloud.config.PropertySource;
import org.springframework.cloud.config.server.ConfigServerProperties;
import org.springframework.cloud.config.server.EncryptionController;
import org.springframework.cloud.config.server.JGitEnvironmentRepository;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import freemarker.cache.NullCacheStorage;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
@RestController
public class NgnixEnvironmentController {
private JGitEnvironmentRepository repository;
private EncryptionController encryption;
private Configuration freemarker;
@Autowired
public NgnixEnvironmentController(JGitEnvironmentRepository repository, EncryptionController encryption)
throws IOException {
this.repository = repository;
this.encryption = encryption;
freemarker = new Configuration(Configuration.VERSION_2_3_21);
freemarker.setCacheStorage(new NullCacheStorage());
freemarker.setDirectoryForTemplateLoading(repository.getBasedir());
}
@RequestMapping(value = "/ngnix/{profiles}", produces = "text/plain")
public String renderConfigFor(@PathVariable String profiles) throws IOException, TemplateException {
return renderConfigFor(profiles, ConfigServerProperties.MASTER);
}
@RequestMapping(value = "/ngnix/{profiles}/{label}", produces = "text/plain")
public String renderConfigFor(@PathVariable String profiles, @PathVariable String label) throws IOException,
TemplateException {
Environment environment = encryption.decrypt(repository.findOne("ngnix", profiles, label));
List<PropertySource> sources = new ArrayList<>(environment.getPropertySources());
Collections.reverse(sources);
Map<Object, Object> dataModel = new HashMap<>();
for (PropertySource source : sources) {
Map<?, ?> values = source.getSource();
dataModel.putAll(values);
}
Template template = freemarker.getTemplate("ngnix.ftl");
StringWriter out = new StringWriter();
template.process(dataModel, out);
String config = out.toString();
return config;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment